1.准备驱动包
mysql
mysql-connector-java
5.1.47
org.postgresql
postgresql
42.2.2
com.microsoft.sqlserver
mssql-jdbc
7.0.0.jre8
分别准备了mysql,postgresql和sqlserver,可以打开jar,发现每个jar包的META-INF/services/都存在一个java.sql.Driver文件,文件里面存在一个或多个类名,比如mysql:
com.mysql.jdbc.Driver
com.mysql.fabric.jdbc.FabricMySQLDriver
提供的每个驱动类占据一行,解析的时候会按行读取,具体使用哪个会根据url来决定;
2.简单实例
String url = “jdbc:mysql://localhost:3306/db3”;
String username = “root”;
String password = “root”;
String sql = “update travelrecord set name=‘bbb’ where id=1”;
Connection con = DriverManager.getConnection(url, username, password);
类路径下存在多个驱动包,具体在使用DriverManager.getConnection应该使用哪个驱动类会解析url来识别,不同的数据库有不同的url前缀;
3.驱动类加载分析
具体META-INF/services/下的驱动类是什么时候加载的,DriverManager有一个静态代码块:
static {
loadInitialDrivers();
println(“JDBC DriverManager initialized”);
}
private static void loadInitialDrivers() {
String drivers;
try {
drivers = AccessController.doPrivileged(new PrivilegedAction() {
public String run() {
return System.getProperty(“jdbc.drivers”);
}
});
} catch (Exception ex) {
drivers = null;
}
// If the driver is packaged as a Service Provider, load it.
// Get all the drivers through the classloader
// exposed as a java.sql.Driver.class service.
// ServiceLoader.load() replaces the sun.misc.Providers()
AccessController.doPrivileged(new PrivilegedAction() {
public Void run() {
ServiceLoader loadedDrivers = ServiceLoader.load(Driver.class);
Iterator driversIterator = loadedDrivers.iterator();
/* Load these drivers, so that they can be instantiated.
-
It may be the case that the driver class may not

本文介绍了KafkaEagle的使用教程,并深入分析了Java的SPI(Service Provider Interface)机制。通过示例展示了如何加载不同数据库驱动,探讨了DriverManager类的加载流程,包括系统变量和ServiceLoader加载方式。文章还提到了驱动类的静态注册过程,并分享了作者的个人经历和Java开发者的学习资源。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



