ConnectionTest.java
package com.demo.connection;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectionTest {
// 方式一
@Test
public void testConnection1() throws SQLException {
Driver driver = new com.mysql.cj.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/erp";
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "root");
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
// 方式二:对方式一的迭代,在如下的程序中不出现第三方的api,使得程序具有更好地移植性
@Test
public void testConnection2() throws SQLException, ClassNotFoundException, InstantiationException, IllegalAccessException {
// 1.获取driver 实现对象:使用反射
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
// 2.提供要连接的数据库
String url = "jdbc:mysql://localhost:3306/erp";
// 3.提供要连接的用户名和密码
Properties info = new Properties();
info.setProperty("user", "root");
info.setProperty("password", "root");
// 4.获取连接
Connection conn = driver.connect(url, info);
System.out.println(conn);
}
// 方式三:使用DriverManager替换Driver
@Test
public void testConnection3() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
// 注册驱动
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
DriverManager.registerDriver(driver);
// 获取连接
String url = "jdbc:mysql://localhost:3306/erp";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
// 方式四:可以只是加载驱动, 对方式三的迭代
@Test
public void testConnection4() throws ClassNotFoundException, SQLException {
// 注册驱动
Class.forName("com.mysql.cj.jdbc.Driver");
// 获取连接
String url = "jdbc:mysql://localhost:3306/erp";
String user = "root";
String password = "root";
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
// 方式五: 将数据库连接信息放在配置文件中
@Test
public void testConnection5() throws IOException, ClassNotFoundException, SQLException {
// 1.读取配置文件中的配置信息
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
// 2.加载驱动
Class.forName(driverClass);
// 3.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println(conn);
}
}
jdbc.properties
user=root
password=root
url=jdbc:mysql://localhost:3306/erp
driverClass=com.mysql.cj.jdbc.Driver