JDBC工具类的主要是封装通用的获取数据库连接对象、释放资源等操作,减少重复代码的编写。在使用JDBC操作数据库时,每次都需要进行数据库连接、资源释放等操作,这会使得代码显得繁琐。我们抽象出一个工具类,可以将这些重复性的操作封装起来,提高代码的简洁性和可维护性。
在src目录下创建一个resources包,并创建配置文件 :db.properties
classDriver=com.mysql.cj.jdbc.Driver
dbUrl=jdbc:mysql://localhost:3306/demo
user=(填写自己数据库用户名)
password=(填写自己数据库密码)
import java.sql.*;
import java.util.ResourceBundle;
public class jdbcUtil {
private static String classDriver;
private static String dbUrl;
private static String user;
private static String password;
static {
//静态代码块
ResourceBundle bundle = ResourceBundle.getBundle("resources/db");
classDriver = bundle.getString("classDriver");
dbUrl = bundle.getString("dbUrl");
user = bundle.getString("user");
password = bundle.getString("password");
//加载驱动
try {
Class.forName(classDriver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//创建链接
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(dbUrl, user, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return connection;
}
//释放资源
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Statement statement, Connection connection) {
if (statement != null) {
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}