Mysql - Class.forName("com.mysql.cj.jdbc.Driver") 做了什么

2021-01-13 14:34:00 浏览数 (1)

常见的加载Mysql jdbc驱动的代码如下:

代码语言:javascript复制
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/datamiddle?characterEncoding=utf8&useSSL=true&rewriteBatchedStatements=true";
String username = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();
那么Class.forName("com.mysql.cj.jdbc.Driver")做了什么呢?

下面是mysql-connector-java 8.0.17的源码,可以看出Driverstatic方法中完成了驱动注册DriverManager.registerDriver(new Driver());

代码语言:javascript复制
package com.mysql.cj.jdbc;

import java.sql.DriverManager;
import java.sql.SQLException;

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!");
        }
    }
}

如果我们在代码中将Class.forName("com.mysql.cj.jdbc.Driver");替换为DriverManager.registerDriver(new Driver());,实现功能是一样的:

代码语言:javascript复制
DriverManager.deregisterDriver(new Driver());
String url = "jdbc:mysql://localhost:3306/datamiddle?characterEncoding=utf8&useSSL=true&rewriteBatchedStatements=true";
String username = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement();

0 人点赞