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

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

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());

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());,实现功能是一样的:

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();

你可能感兴趣的:(Mysql - Class.forName("com.mysql.cj.jdbc.Driver") 做了什么)