注册驱动时通过 Class.forName("com.mysql.jdbc.Driver") 加载类并执行类初始化方法 <
cinit> ,其中会调用 java.sql.DriverManager.registerDriver(new Driver())真钱麻将,把当前 Driver 包装成一个DriverInfo 放入到一个 DriverManager COW list 中真钱麻将,即 CopyOnWriteArrayList<
DriverInfo> registeredDrivers。public class Driver extends NonRegisteringDriver implements java.sql.Driver {
//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
/**
* Construct a new driver and register it with DriverManager
*
* @throws SQLException if a database error occurs.
*/
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}
获取连接 DriverManager.getConnection() 时会遍历已经注册在 registeredDrivers 中的 DriverInfo,调用 connect 建立连接最终返回一个 java.sql.Connection。private static Connection getConnection(
// ...
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());
}
}
// ...
}