使用JDBC来连接MySQL数据库,在各个方法中都要添加驱动、建立连接、释放资源等,会造成代码的冗余和复杂,所以将相同部分抽取出来,建立一个JDBCUtil的工具类,从.properties配置文件中读取数据,进行驱动和连接部分的实现,使用时直接调用即可。
package com.thoughtworks.Util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Objects;
import java.util.Properties;
public class JDBCUtil {
private static String URL;
private static String USER;
private static String PASSWORD;
private static String DRIVER;
static{
//读取资源文件,获取相应的值
try {
//1.创建Properties集合类
Properties prop = new Properties();
//获取src路径下的文件的方式---->ClassLoader类加载器
URL pathURL = JDBCUtil.class.getClassLoader().getResource("jdbc.properties");
String path = Objects.requireNonNull(pathURL).getPath();
//2.加载文件
prop.load(new FileReader(path));
//3.获取数据、赋值
URL = prop.getProperty("url");
USER = prop.getProperty("user");
PASSWORD = prop.getProperty("password");
DRIVER = prop.getProperty("driver");
//注册驱动
Class.forName(DRIVER);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(URL, USER, PASSWORD);
}
public static void releaseSource(Statement stmt, Connection conn) {
if(null != stmt) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(null != conn) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void releaseSource(ResultSet res, Statement stmt, Connection conn) {
if(null != res) {
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
releaseSource(stmt,conn);
}
}