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;
/**
* @author JessieWu
* @create 2020-09-02 18:37
*/
public class ConnectionTest {
//方式一:
@Test
public void testConnection1() throws SQLException {
//获取Driver的实现类对象
Driver driver = new com.mysql.cj.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=UTC";
//用户名和密码
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","3267754ww");
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
//方式二:对方式一的一个迭代
@Test
public void testConnection2() throws Exception {
//获取Driver的实现类对象,利用反射来实现
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=UTC";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","3267754ww");
Connection connect = driver.connect(url, info);
System.out.println(connect);
}
//方式三:使用DriverManager来代替
@Test
public void testConnection() throws Exception {
//1.获取Driver实现类的对象
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver o = (Driver) clazz.newInstance();
//2.提供另外三个链接的基本信息
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=UTC";
String user = "root";
String password = "3267754ww";
//注册驱动
DriverManager.registerDriver(o);
//获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式四:使用DriverManager来代替的优化
@Test
public void newtestConnection() throws Exception {
//1.提供另外三个链接的基本信息
String url = "jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&serverTimezone=UTC";
String user = "root";
String password = "3267754ww";
//2.获取Driver实现类的对象,可以省略是因为有静态代码块,自动加载注册了
Class.forName("com.mysql.cj.jdbc.Driver");
// Driver o = (Driver) clazz.newInstance();
// //注册驱动
// DriverManager.registerDriver(o);
//3.获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
//方式五:最终版,将数据库链接需要的4个基本信息封装到配置文件
@Test
public void lastVersion() throws IOException, ClassNotFoundException, SQLException {
//1.读取配置文件中的4个基本信息
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties props = new Properties();
props.load(is);
String user = props.getProperty("user");
String password = props.getProperty("password");
String url = props.getProperty("url");
String driverClass = props.getProperty("driverClass");
//2.加载驱动
Class.forName(driverClass);
//3.获取连接
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
网友评论