本篇對(duì)jdbc的獲取連接進(jìn)行解析
1.這里是直接上代碼哈壕曼,它的getConnection會(huì)通過(guò)相對(duì)應(yīng)調(diào)用的重載方法來(lái)進(jìn)行不同的操作,我們主要看我們常規(guī)的連接方式迹淌。
@CallerSensitive
public static Connection getConnection(String url,
String user, String password) throws SQLException {
//存放相關(guān)配置屬性
java.util.Properties info = new java.util.Properties();
if (user != null) {
info.put("user", user);
}
if (password != null) {
info.put("password", password);
}
//會(huì)繼續(xù)調(diào)用本類getConnection方法,并傳入反射的getCallerClass方法撒汉。
return (getConnection(url, info, Reflection.getCallerClass()));
}
繼續(xù)之前需要解釋一下@CallerSensitive
@CallerSensitive開(kāi)發(fā)者正常調(diào)用是不起作用的芭概,因?yàn)閖ava并不希望我們調(diào)用該方法。(它也是可以被調(diào)用的位喂, -Xbootclasspath/a: path 在jvm啟動(dòng)進(jìn)行配置)它必須有啟動(dòng)類ClassLoader加載(比如rt.jar才能被識(shí)別)浪耘。
Reflection.getCallerClass()這個(gè)方法就必須加上@CallerSensitive配合使用。
它這里是做什么用的忆某?点待?
2.然后我們繼續(xù)往下看(看注解哦)
// Worker method called by the public getConnection() methods.
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.
*/
//這里的話就基本大概知道為什么了,它在這里的話就會(huì)通過(guò)它來(lái)獲取的我們的數(shù)據(jù)庫(kù)連接的驅(qū)動(dòng)弃舒。
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;
//這里的話就會(huì)獲取完后并通過(guò)配置進(jìn)行連接,最后返回Connection癞埠。
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());
}
}
//如果走到這里就是百分百有問(wèn)題啦,就是報(bào)錯(cuò)的原因會(huì)在這拋出聋呢。
// if we got here nobody could connect.
if (reason != null) {
println("getConnection failed: " + reason);
throw reason;
}
//走到這里的話就是找不到合適的驅(qū)動(dòng)
println("getConnection: no suitable driver found for "+ url);
throw new SQLException("No suitable driver found for "+ url, "08001");
}