package com.lwb.connection;
import org.junit.jupiter.api.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 = new com.mysql.jdbc.Driver();
String url="jdbc:mysql://localhost:3306/test";
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","1234");
Connection conn =driver.connect(url,info);
System.out.println("test1: "+conn);
}
// 对方式一的迭代:在如下的程序中不会出现第三方的api,使得程序具有更好的可移植性。
@Test
public void testConnextion2() throws Exception {
// 1、获取java实现类对象,使用反射
Class clazz =Class.forName("com.mysql.jdbc.Driver");
Driver driver=(Driver) clazz.newInstance();
// 2、提供要连接的数据库
String url="jdbc:mysql://localhost:3306/test";
// 3、提供连接需要的用户名和密码
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","1234");
// 4、获取连接
Connection conn=driver.connect(url,info);
System.out.println("test2: "+conn);
}
// 方式三:使用DriverManger替换Driver
@Test
public void testConnection3() throws Exception{
// 1、获取Driver实现类的对象
Class clazz=Class.forName("com.mysql.jdbc.Driver");
Driver driver=(Driver) clazz.newInstance();
// 2、提供账号密码和url
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="1234";
// 3、注册驱动
DriverManager.registerDriver(driver);
// 4、获取连接
Connection conn=DriverManager.getConnection(url,user,password);
System.out.println("test3: "+conn);
}
//方式四:可以只加载驱动,不用显示的注册驱动了。
@Test
public void testConnection4() throws Exception {
String url="jdbc:mysql://localhost:3306/test";
String user="root";
String password="1234";
//加载driver
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(url,user,password);
System.out.println("test4: "+conn);
}
//方式5:用配置文件获取参数
@Test
public void testConnection5() throws Exception{
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");
//加载驱动
Class.forName(driverClass);
//获取连接
Connection conn=DriverManager.getConnection(url,user,password);
System.out.println("test5: "+conn);
}
}
jdbc.properties文件:
user=root
password=1234
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver