package jdbc1_test;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import org.junit.Test;
import com.mysql.cj.jdbc.Driver;
public class Connectiontest {
//方式一
@Test
public void testConnection1() throws Exception {
//1、获取Driver实现类的对象
Class clazz=Class.forName("com.mysql.cj.jdbc.Driver");
Driver driver=(Driver)clazz.newInstance();
//2、提供另外三个连接的基本信息
String url="jdbc:mysql://localhost:3308/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
String user="root";
String password="123456";
//注册驱动
DriverManager.registerDriver(driver);
//获取连接
Connection conn=DriverManager.getConnection(url, user,password);
System.out.println(conn);
}
//方式二
@Test
public void testConnection2() throws Exception {
//1、提供另外三个连接的基本信息
String url="jdbc:mysql://localhost:3308/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
String user="root";
String password="123456";
//2、加载Driver
Class.forName("com.mysql.cj.jdbc.Driver");
//相较于方式一,可以省略以下操作,在mysql的driver实现类中自动实现了驱动
// Driver driver=(Driver)clazz.newInstance();
// //注册驱动
// DriverManager.registerDriver(driver);
//3、获取连接
Connection conn=DriverManager.getConnection(url, user,password);
System.out.println(conn);
}
//方式三:最终版
//将数据库连接需要的这四个基本信息声明在配置文件中,通过读取配置文件的方式,获取连接
@Test
public void testConnection3() throws Exception {
//读取配置文件中的四个基本信息
InputStream is=Connectiontest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pro=new Properties();
pro.load(is);
String user=pro.getProperty("user");
String password=pro.getProperty("password");
String url=pro.getProperty("url");
String driverClass=pro.getProperty("driverClass");
//加载驱动
Class.forName(driverClass);
//获取连接
Connection conn=DriverManager.getConnection(url, user,password);
System.out.println(conn);
}
}
注:本人因使用php方便所以mysql的端口号使用的是3308
其中,配置文件【jdbc.properties】:此配置文件声明在工程的src下
user=root ;
password=123456 ;
url=jdbc:mysql://localhost:3308/test?rewriteBatchedStatements=true ;
driverClass=com.mysql.jdbc.Driver;
注意:在mysql 8.0版本以后url的设置需要加上进行修改
url="jdbc:mysql://localhost:3308/test?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
驱动driverClass也要修改为
driverClass=com.mysql.cj.jdbc.Driver