package connection;
import org.testng.annotations.Test;
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 driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
//获取用户名密码
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "960614sd");
//获取连接
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
// 方式二:为了代码的可移植性,希望在代码中不要出现任何具体的第三方的API
@Test
public void testConnection2() throws Exception {
//使用反射获取Driver的实现类对象
Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").getDeclaredConstructor().newInstance();
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
Properties properties = new Properties();
properties.setProperty("user", "root");
properties.setProperty("password", "960614sd");
Connection connection = driver.connect(url, properties);
System.out.println(connection);
}
//方式三:为了统一管理各个driver,将driver注册到DriverManager中,使用DriverManager进行数据库连接
@Test
public void testConnection3() throws Exception {
//使用反射获取Driver的实现类对象
Driver driver = (Driver) Class.forName("com.mysql.jdbc.Driver").getDeclaredConstructor().newInstance();
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "960614sd";
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式四:从阅读mysql驱动类源码来优化方式三,只需加载驱动类,无需显示的注册驱动
@Test
public void testConnection4() throws Exception {
String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
String user = "root";
String password = "960614sd";
//加载驱动类
//驱动类中有DriverManager.registerDriver(new Driver())的静态代码块,无需再手动注册
//其实加载类的操作也可以省略,因为在链接mysql驱动的时候会自动加载驱动类,但是其他数据库厂商的驱动不会自动帮你加载驱动类,所以不应省略
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式五:将连接信息写入配置文件,通过配置文件进行连接,代码更加解耦
@Test
public void testConnection5() throws Exception {
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(is);
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driverClass = properties.getProperty("driverClass");
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}