注册驱动
DriverManager.registerDriver()方式注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 该方式会注册2个驱动,mysql的Driver里面有个静态代码块,里面有注册驱动的代码。如图:
Class.forName()方式注册驱动
Class.form(“com.mysql.jdbc.Driver”); // 在java.sql.DriverManager类描述有这么一段话
The DriverManager methods getConnection and getDrivers have been enhanced to support
the Java Standard Edition Service Provider mechanism. JDBC 4.0 Drivers mustinclude the
file META-INF/services/java.sql.Driver. This file contains the name of the JDBC
driversimplementation of java.sql.Driver. For example, to load the my.sql.Driver class,
the META-INF/services/java.sql.Driver file would contain the entry:
my.sql.Driver
Applications no longer need to explicitly load JDBC drivers using Class.forName().
Existing programswhich currently load JDBC drivers using Class.forName() will
continue to work withoutmodification.
翻译出来的意思就是:DriverManager方法getConnection和getDrivers已经得到了增强,以支持Java标准版服务提供程序机制。JDBC 4.0驱动程序
必须包含文件META-INF/services/java.sql.Driver。这个文件包含java.sql.Driver的JDBC driversimplementation的名称。例如,加载my.sql。驱动程序类,META-INF /services/java.sql.Driver。驱动程序文件将包含条目:
my.sql.Driver
应用程序不再需要使用Class.forName()显式加载JDBC驱动程序
。目前使用Class.forName()加载JDBC驱动程序的现有程序将继续工作而不需要修改。
这个意思就是在JDBC4.0以后的版本可以不写加载驱动的代码,照样可以连接数据库进行操作。