MySQL to drive for example, describes three ways to register the driver's
1: Class.forName ( "com.mysql.cj.jdbc.Driver"); // load the database driver
. 1 Package com.pine.interview.jdbc; 2 . 3 Import the java.sql.Connection; . 4 Import the java.sql.DriverManager; . 5 Import java.sql.SQLException; . 6 . 7 public class Driver1 { . 8 public static void main (String [] args) throws a ClassNotFoundException, SQLException { . 9 the Class.forName ( "com.mysql.cj.jdbc.Driver"); // load database driver 10 String URL = "JDBC: MySQL: // localhost: 3306 / Pine serverTimezone = UTC? "; // database connection sub-protocol 11 Connection conn = DriverManager.getConnection(url, "root", "root"); 12 System.out.println(conn); 13 conn.close(); 14 } 15 }
2: System.setProperty ( "jdbc.drivers", "com.mysql.cj.jdbc.Driver"); // load database driver
. 1 Package com.pine.interview.jdbc; 2 . 3 Import the java.sql.Connection; . 4 Import the java.sql.DriverManager; . 5 Import java.sql.SQLException; . 6 . 7 public class Driver2 { . 8 public static void main (String [] args) throws a ClassNotFoundException, SQLException { . 9 System.setProperty ( "the jdbc.drivers", "com.mysql.cj.jdbc.Driver"); // load database driver 10 String URL = "JDBC: MySQL: // localhost: 3306 ? / Pine serverTimezone UTC = "; // database connection sub-protocol 11 Conn = the DriverManager.getConnection Connection (URL, "the root", "the root" ); 12 is System.out.println (Conn); 13 is conn.Close (); 14 / ** 15 * may be introduced simultaneously driving a plurality of jdbc intermediate colon ":" separated 16 such System.setProperty ( "the jdbc.drivers", "XXXDriver: XXXDriver: XXXDriver"); . 17 * / 18 is } . 19 }
3: new com.mysql.cj.jdbc.Driver (); // load database driver
. 1 Package com.pine.interview.jdbc; 2 . 3 Import the java.sql.Connection; . 4 Import the java.sql.DriverManager; . 5 Import java.sql.SQLException; . 6 . 7 public class Driver3 { . 8 public static void main (String [] args) throws SQLException { . 9 new new com.mysql.cj.jdbc.Driver (); // load database driver 10 String URL = "JDBC: MySQL: // localhost: 3306 / Pine serverTimezone = UTC?"; // database connection sub-protocol 11 Connection conn = DriverManager.getConnection(url, "root", "root"); 12 System.out.println(conn); 13 conn.close(); 14 } 15 }
Recommended Method 1, Method 2, Method 2 wherein the plurality of driving time registration can
Method 3 is not recommended, because it will compile-time dependencies mysql driver package, and a static block will register for driving, examples of the new Driver out superfluous useless
As shown below: