本文章以mysql为例,文章的不足欢迎吐槽。
相信很多人都会使用jdbc创建数据连接。
static String driverName = "com.mysql.jdbc.Driver";
static String url = "jdbc:mysql://127.0.0.1:3306/mysql";
static String username = "root";
static String password = "";
@Test
public void getConnection1() {
try {
// 1、加载驱动
Class.forName(driverName);
// 2、获取connection
Connection conn = DriverManager.getConnection(url,username,password);
System.out.println(conn);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
代码可以说是非常简单,但是仔细想一下,发现会有2两疑问:
-
Class.forName(driverName)这样加载去驱动,又没有创建进行赋值给某个变量,DriverManager是如何使用该驱动来创建连接的?
-
如果换成别的数据库,只需要把Mysql的驱动换成别的数据库驱动就可以了,其它的代码不用改,这是怎么做到的?
下面进行解答👇
疑问1:
Class.forName(className)这个方法是会执行className这个类的静态代码块的。在我们执行Class.forName("com.mysql.jdbc.Driver")的时候,com.mysql.jdbc.Driver这个类的静态代码块会被执行,然后向DriverManager注册驱动
下面是com.mysql.jdbc.Driver的源码
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!");
}
}
其它省略
}
疑问2:
这个很简单,定义驱动的接口就可以了,然后交由DriverManager驱动管理器进行管理。jdbc只是定义了java数据库连接的标准,具体的实现是各个数据库厂商实现的。
java.sql.Driver源码
public interface Driver {
// 要把 username、password等信息put到Properties里面
Connection connect(String url, java.util.Properties info)
throws SQLException;
boolean acceptsURL(String url) throws SQLException;
DriverPropertyInfo[] getPropertyInfo(String url, java.util.Properties info)
throws SQLException;
int getMajorVersion();
int getMinorVersion();
boolean jdbcCompliant();
//------------------------- JDBC 4.1 -----------------------------------
public Logger getParentLogger() throws SQLFeatureNotSupportedException;
}
在调用DriverManager.getConnection()的时候,DriverManager其实是使用厂商提供的驱动包内java.sql.Driver的实现类来获取connection的,如果mysql就是使用com.mysql.jdbc.Driver内connect()方法进行连接数据库获取connection。
如果我们不是用DriverManager,那应该怎样获取connection呢??
很简单直接调用java.sql.Driver实现类的connect()方法就可以了。
@Test
public void getConnnection2() {
try {
// 通过反射创建驱动对象
Driver driver = (Driver) Class.forName(driverName).newInstance();
// 你也可以这样写,但是这样耦合太大了
// com.mysql.jdbc.Driver driver = new com.mysql.jdbc.Driver();
// 包装连接信息
Properties info = new Properties();
info.put("user", username);
info.put("password", password);
// 获取连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
网友评论