获取连接
小于 1 分钟数据库技术JDBC
public class JdbcTest {
/**
* 1、完整流程
*/
@Test
public void test1() throws SQLException {
// 1.定义要素
String driverName = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8&&useSSL=false&serverTimezone=GMT%2B8";
String username = "root";
String password = "root";
// 2.加载驱动,实例化驱动
Driver driver = new Driver();
// 3.注册驱动
DriverManager.registerDriver(driver);
// 4.获取连接
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
}
/**
* 2、反射加载驱动
*/
@Test
public void test2() throws SQLException, ClassNotFoundException {
// 1.定义要素
String driverName = "com.mysql.cj.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8&&useSSL=false&serverTimezone=GMT%2B8";
String username = "root";
String password = "root";
// 2.加载驱动,实例化驱动。并注册驱动
// 仅仅需要jvm加载一下
Class.forName(driverName);
// 4.获取连接
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
}
/**
* 3、jvm主动加载驱动:SPI机制
*/
@Test
public void test3() throws SQLException {
// 1.定义要素
String url = "jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8&&useSSL=false&serverTimezone=GMT%2B8";
String username = "root";
String password = "root";
// 4.获取连接
Connection connection = DriverManager.getConnection(url, username, password);
System.out.println(connection);
}
}
结果:
com.mysql.cj.jdbc.ConnectionImpl@37d31475
Process finished with exit code 0
我们并没有加载驱动,但是获取到了MySQL的驱动实现。这是JDK主动加载的,涉及到SPI机制。