源码解析 - JDBC

获取 JDBC 连接的代码如下

//使用调用者的类加载器,加载全限定名指定的类
Class.forName("com.mysql.jdbc.Driver");
//通过已注册的 JDBC 驱动,根据参数获取数据库连接
conn = DriverManager.getConnection(DB_URL,USER,PASS);

查看 com.mysql.jdbc.Driver 的静态代码块(在类被加载时执行)

public class Driver extends NonRegisteringDriver implements java.sql.Driver {

    //通过 DriverManager 注册当前驱动(JDBC for MySql)
    static {
        try {
            java.sql.DriverManager.registerDriver(new Driver());
        } catch (SQLException E) {
            throw new RuntimeException("Can't register driver!");
        }
    }
}

继续查看 DriverManager 的 registerDriver()

public class DriverManager {

    //已注册 JDBC 驱动的列表
    private final static CopyOnWriteArrayList<DriverInfo> registeredDrivers = new CopyOnWriteArrayList<>();

    //......

    public static synchronized void registerDriver(java.sql.Driver driver)
        throws SQLException {

        registerDriver(driver, null);
    }

    public static synchronized void registerDriver(java.sql.Driver driver,
            DriverAction da)
        throws SQLException {

        /* Register the driver if it has not already been added to our list */
        if(driver != null) {
            registeredDrivers.addIfAbsent(new DriverInfo(driver, da));
        } else {
            // This is for compatibility with the original DriverManager
            throw new NullPointerException();
        }

        println("registerDriver: " + driver);

    }
}

可以看到 Class.forName(“com.mysql.jdbc.Driver”); 的作用就是往 DriverManager 里注册一个 JDBC 驱动


接着查看 DriverManager 的 getConnection() 方法源码

    @CallerSensitive
    public static Connection getConnection(String url,
        String user, String password) throws SQLException {
        java.util.Properties info = new java.util.Properties();

        if (user != null) {
            info.put("user", user);
        }
        if (password != null) {
            info.put("password", password);
        }

        //第三个参数为调用者的类
        return (getConnection(url, info, Reflection.getCallerClass()));
    }

    //......

    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.
         */
        //如果存在调用者的类,就使用调用者的类加载器
        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");
    }

这就是获取 JDBC 连接的全过程,值得一提的是上面多行注释里提到的:如果调用者的类加载器为 null,尝试使用应用程序的类加载器,所以在 rt.jar 外部的 JDBC 驱动类允许被加载(JDK 里默认存在三种类加载器,不同加载器可加载类的范围不一样,其中应用程序类加载器可加载 ClassPath 下的所有类库)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值