import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.security.PublicKey;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
/**
* @Author HLY
* @Create 2019-12-04 17:13
*/
public class ConnectionTest {
//方式一
@Test
public void test() throws SQLException {
Driver driver=new com.mysql.cj.jdbc.Driver();
String s ="jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai" ;
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","root");
Connection connect = driver.connect(s, info);
System.out.println(connect);
}
//方式二
@Test
public void test1() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver= (Driver) clazz.newInstance();
String s ="jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai" ;
Properties info=new Properties();
info.setProperty("user","root");
info.setProperty("password","root");
Connection connect = driver.connect(s, info);
System.out.println(connect);
}
//方式三
@Test
public void test2() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
//获取Driver实现的对象
Class clazz = Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver= (Driver) clazz.newInstance();
//注册驱动
DriverManager.registerDriver(driver);
//获取链接
String s ="jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai" ;
Connection connection = DriverManager.getConnection(s, "root", "root");
System.out.println(connection);
}
//方式四:只是加载驱动,不用显示的注册驱动
@Test
public void test3() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException {
//加载驱动
Class.forName("com.mysql.cj.jdbc.Driver");
//获取链接
String s ="jdbc:mysql://localhost:3306/test?serverTimezone=Asia/Shanghai" ;
Connection connection = DriverManager.getConnection(s, "root", "root");
System.out.println(connection);
}
//方式五:配置文件方式
@Test
public void test4() throws ClassNotFoundException, IllegalAccessException, InstantiationException, SQLException, IOException {
InputStream inputStream=ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties=new Properties();
properties.load(inputStream);
String user=properties.getProperty("user");
String password=properties.getProperty("password");
String url=properties.getProperty("url");
String driverClass=properties.getProperty("driverClass");
Class.forName(driverClass);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}