常见的加载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
的源码,可以看出Driver
在static
方法中完成了驱动注册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();