JDBC 学习笔记 day01
获取数据库连接
说明:如下的多种方法,是以迭代的形式给出的,实际使用中只需记住最后一种方式,但了解迭代的过程也是很重要的。
@Test
//方式一:
public void test() throws Exception {
//1.获取 Driver 类的实现类对象
String driver = "com.mysql.cj.jdbc.Driver";
Class clazz = Class.forName(driver);
Driver d = (Driver) clazz.getDeclaredConstructor().newInstance();
//2.提供要连接的数据库
String url = "jdbc:mysql://localhost:3306/test";
//3.提供用户名和密码
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "yuyingjie123");
//4.获取连接
Connection con = d.connect(url, properties);
System.out.println(con);
}
@Test
//方式二:通过 DriverManager 类来实现连接的获取
public void test1() throws Exception {
//1.提供三个基本信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "yuyingjie123";
//2.获取 Driver 类的实现类对象
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver d = (Driver) clazz.getDeclaredConstructor().newInstance();
//3.注册驱动
DriverManager.registerDriver(d);
//4.获取连接
Connection con = DriverManager.getConnection(url, user, password);
System.out.println(con);
}
@Test
//方式三:
public void test2() throws Exception {
//1.提供三个基本信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "yuyingjie123";
Class.forName("com.mysql.cj.jdbc.Driver");
//如下的操作可以省略
//2.获取 Driver 类的实现类对象
// Driver d = (Driver) clazz.getDeclaredConstructor().newInstance();
//
// //3.注册驱动
// DriverManager.registerDriver(d);
/*因为在 com.mysql.cj.jdbc.Driver 类中有静态方法
static {
try {
DriverManager.registerDriver(new Driver());
} catch (SQLException var1) {
throw new RuntimeException("Can't register driver!");
}
}
在类加载的时候就已经执行了注册驱动的操作
*/
//4.获取连接
Connection con = DriverManager.getConnection(url, user, password);
System.out.println(con);
}
@Test
/*
方式四(最终版):通过用配置文件存储信息
好处:1.实现了数据和代码的分离,实现了解耦
2.如果需要修改配置文件,可避免程序的重新打包
*/
public void test3() throws Exception {
//1.提供四个个基本信息
ClassLoader scl = ClassLoader.getSystemClassLoader();
InputStream is = scl.getResourceAsStream("data.properties");
Properties pro = new Properties();
pro.load(is);
String user = pro.getProperty("user");
String password = pro.getProperty("password");
String url = pro.getProperty("url");
String className = pro.getProperty("className");
//2.注册驱动
Class.forName(className);
//4.获取连接
Connection con = DriverManager.getConnection(url, user, password);
System.out.println(con);
}