try
{
Class.forName("com.mysql.jdbc.Driver");
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch (ClassNotFoundException e)
{
logger.error("driver not exists.", e);
}
- 當注冊了多個driver時炼绘,下面的代碼到底是怎么選擇driver的呢?
Connection connection = DriverManager.getConnection(url, user, pwd);
首先道媚,class.forName("xxx“)觸發(fā)Driver實現(xiàn)類的加載時,Driver實現(xiàn)的static塊會向DriverManager注冊該Driver黔攒。
比如:mysql 的diver是這樣的:
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!");
}
}
}
然后DriverManager會一個一個驅(qū)動去試黄娘,哪個驅(qū)動能連接上數(shù)據(jù)庫就使用那個驅(qū)動:
private static Connection getConnection(
String url, java.util.Properties info, Class<?> caller) throws SQLException {
/*
* When callerCl is null, we should check the application's
* (which is invoking this class indirectly)
* classloader, so that the JDBC driver class outside rt.jar
* can be loaded from here.
*/
//caller的類加載器優(yōu)先
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");
}
}
- 類權限判斷
DriverManager先通過isDriverAllowed(aDriver.driver, callerCL)
判斷調(diào)用方(通過Connection connection = DriverManager.getConnection(url, user, pwd);
獲取連接的業(yè)務代碼)的加載器在加載Driver實現(xiàn)類(通過名字)之后的直接類加載器是否等于已注冊Driver類的類加載器伶贰,如果相等绕辖,才嘗試去connect脓诡。
這么做一方面能保證Driver實現(xiàn)類在整個系統(tǒng)不會出現(xiàn)被多個classLoader直接加載无午,也就是只有一個namespace,另一方面也防止了業(yè)務代碼執(zhí)行Connection connection = DriverManager.getConnection(url, user, pwd);
時出現(xiàn)ClassNotFound祝谚。