记录一次DriverManager.getConnection 引入的坑

120 阅读1分钟

背景

最近发现一个奇怪的问题,测试一种数据源链接的时候,会报错,报错的jar包是另一种数据源所依赖的

原因:

DriverManager已经在静态代码块中帮我们创建了Driver对象了。那DriverManager怎么知道具体要创建哪个对象呢?

其实在DriverManger会根据jar包中的java.sql.Driver文件的内容来创建Driver对象

image.png

image.png

解决办法

用 new Driver().connect()方法

具体实现

通过new一个Driver对象,并且获取连接

public void connect01() throws Exception {
        String url = "jdbc:mysql://node1:3306/db01";
        String user = "root";
        String password = "123456";
        String driver = "com.mysql.jdbc.Driver";
 
        // 1.这里通过反射获取Driver的Class对象
        Class<?> aClass = Class.forName(DRIVER);
        
        // 2.获取一个Driver对象
        Driver driver = (Driver) aClass.newInstance();
        Properties properties = new Properties();
        properties.setProperty("user", user);
        properties.setProperty("password", password);
 
        // 3.获取连接
        Connection connect = driver.connect(url, properties);
        System.out.println(connect);
    }