-
使用前需导入jar包
- mysql8导入8的jar包
- mysql5导入5的jar包
-
配置文件放置路径,项目的src根目录下:
如:
- 配置文件:jdbc.properties
#mysql8
url=jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8
#mysql5
url=jdbc:mysql://localhost:3306/test
#值也可不用单引号
#数据库连接用户名
user='root'
#数据库用户密码
password=root
#mysql8
driver=com.mysql.cj.jdbc.Driver
#mysql5
#driver=com.mysql.jdbc.Driver
- JDBC工具类:JDBCUtils.java
package com.jdbc.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
//JDBC工具类
public class JDBCUtils {
//定义连接数据库属性
private static String url = null;
private static String user = null;
private static String password = null;
private static String driver = null;
//读取配置文件,static,文件的读取,只需要一次即可拿到连接所需属性
static{
try {
//使用类加载器获取当前类路径
//获取类加载器对象ClassLoader
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
//通过类加载器的getResource()找到指定名称的资源
URL resource = classLoader.getResource("jdbc.properties");
//System.out.println(resource); //file:/D:/java_work/demo4_project/out/production/demo2_jdbc/jdbc.properties
//使用getPath()获取这个URL的路径部分
String path = resource.getPath();
//System.out.println("path:" + path); ///D:/java_work/demo4_project/out/production/demo2_jdbc/jdbc.properties
//加载配置文件
//创建对象
Properties pro = new Properties();
//加载配置文件键值对数据,使用load()从输入字节流或字符流中读取属性列表
pro.load(new FileReader(path));
//根据键获取属性值,使用getProperty()
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
//注册驱动,类加载就会执行
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//定义获取连接方法,获取数据库连接对象Connection
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
//释放资源
public static void close(ResultSet rs, Statement stat, Connection conn){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stat != null){
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Statement stat, Connection conn){
if (stat != null){
try {
stat.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}