JDBC源码解析(二):获取connection

JerryXia 发表于 , 阅读 (45)

0x00 前言

上一节分析了jdbc的Driver注册过程,这一节分析一下jdbc是如何获取connection的。

0x01 connection的建立过程

DriverManager.getConnection 做了什么

conn = DriverManager.getConnection("jdbc:mysql://192.168.108.145/test", "root", "root");

可以看出,getConnection方法返回的是一个Connection对象,在下面的for循环中,会遍历registeredDrivers中存放的所有的Driver,直到找到一个合适的Driver,然后进行连接。通过这个方法我已经可以知道jdbc就是这样来获取连接的,但是具体是怎么来获取这个connection,还需要详细地看后面的代码。

private static Connection getConnection(        String url, java.util.Properties info, ClassLoader callerCL) throws SQLException {    ......        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);                    }