创建普通的Java项目
新建lib文件夹,并把mysql驱动放进去
Project Structure中添加依赖
在src目录下建立jdbc.properties
user=root
password=123456
url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8&useUnicode=true&useSSL=false
driverClass=com.mysql.cj.jdbc.Driver
建立
package com.geng.connection;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class ConnectionTest {
@Test
public void test1(){
try {
// 1.读取配置文件
InputStream is = ConnectionTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
// 2.读取配置参数
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
// 3.加载驱动
Class.forName(driverClass);
// 4.获取连接
Connection conn = DriverManager.getConnection(url, user, password);
// 打印结果
System.out.println(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}