- 驱动加载,通过SPI机制,不需要Class.forName()加载驱动。
- 可以加载多个驱动
- 循环驱动,尝试连接,连接成功就返回。
驱动加载
DriverManager 在静态代码块中加载驱动,类路径下有多个驱动都会被加载。 ```java package java.sql
public class DriverManager { static { loadInitialDrivers(); println(“JDBC DriverManager initialized”); }
private static void loadInitialDrivers() {
// 加载所有配置在/META-INF/services/java.sql.Driver的驱动实现类
ServiceLoader
MySQL 驱动类的静态代码块中注册驱动。```javapackage com.mysql.cj.jdbc;import java.sql.DriverManager;import java.sql.SQLException;public class Driver extends NonRegisteringDriver implements java.sql.Driver {public Driver() throws SQLException {}static {try {DriverManager.registerDriver(new Driver());} catch (SQLException var1) {throw new RuntimeException("Can't register driver!");}}}
Oracle驱动类的静态代码块中注册驱动。
package oracle.jdbc.driver;@DefaultLogger("oracle.jdbc")@Supports({Feature.CONNECT})public class OracleDriver implements Driver, Monitor {static {if (defaultDriver == null) {defaultDriver = new oracle.jdbc.OracleDriver();DriverManager.registerDriver(defaultDriver, OracleDriver::deregister);}}}
总结:DriverManager 类加载 —> loadInitialDrivers —> ServiceLoader.load(Driver.class) —> next() —> 具体的驱动类加载 —> DriverManager.registerDriver.
获取连接
DriverManager.getConnection是尝试获取连接,本质还是调用Driver.getConnection. 如果直接用Driver.getConnection获取连接就可以确定的获取连接。
java.sql.DriverManagerprivate static Connection getConnection(String url, java.util.Properties info, Class<?> caller) throws SQLException {ClassLoader callerCL = caller != null ? caller.getClassLoader() : null;synchronized(DriverManager.class) {// synchronize loading of the correct classloader.if (callerCL == null) {callerCL = Thread.currentThread().getContextClassLoader();}}if(url == null) {throw new SQLException("The url cannot be null", "08001");}println("DriverManager.getConnection(\"" + url + "\")");// Walk through the loaded registeredDrivers attempting to make a connection.// Remember the first exception that gets raised so we can reraise it.SQLException reason = null;//循环尝试获取连接,获取就返回for(DriverInfo aDriver : registeredDrivers) {// If the caller does not have permission to load the driver then skip it.if(isDriverAllowed(aDriver.driver, callerCL)) {try {println(" trying " + aDriver.driver.getClass().getName());Connection con = aDriver.driver.connect(url, info);if (con != null) {// Success!println("getConnection returning "+aDriver.driver.getClass().getName());return (con);}} catch (SQLException ex) {if (reason == null) {reason = ex;}}} else {println(" skipping: " + aDriver.getClass().getName());}}// if we got here nobody could connect.if (reason != null) {println("getConnection failed: " + reason);throw reason;}println("getConnection: no suitable driver found for "+ url);throw new SQLException("No suitable driver found for "+ url, "08001");}
