java中jdbc源码解读

2023-03-02,,

  在jdbc中一个重要的接口类就是java.sql.Driver,其中有一个重要的方法:Connection connect(String url, java.util.Propeties info);从这个方法可以看到,Driver类的作用就是返回一个connection。

public interface DataSource  extends CommonDataSource, Wrapper {
Connection getConnection() throws SQLException;
Connection getConnection(String username, String password)
throws SQLException;
// DaatSource的方法,就是要获取一个Connection,有了Connection,就可以通信了,这就是开发者关心的,其实现细节不需要了解,
//DataSource的意义就在这里
}

  在com.mysql.cj.jdbc.ConnectionImpl类,实现了java.sql.Connection接口,这也是在开发中要加载驱动的原因,其源码27000行,能不能看懂就是你的功力了。在java.sql.DriverManager中看到了Class.forName()函数的调用,说明了在加载sql相关的类。

public class Driver extends NonRegisteringDriver implements java.sql.Driver {
//
// Register ourselves with the DriverManager
//
static {
try {
java.sql.DriverManager.registerDriver(new Driver());
} catch (SQLException E) {
throw new RuntimeException("Can't register driver!");
}
}
public Driver() throws SQLException {
// Required for Class.forName().newInstance()
}
}
最终,获取Connnection的是DriverManager getConnection(String,Properties,Class<?>)这句代码:
Connection con =aDriver.driver.connect(url,info);而com.mysql.cj.jdbc.NonResgisteringDriver类给出了获得Connection的代码。

在springboot2.0中又加入了DataSourceBuilder类,配置数据库连接池,真的是能为程序员做的都做了。

java中jdbc源码解读的相关教程结束。