DbHelper重用性方案 优化工具类 jdbc
为了提升性能
防止每一次调用 获取连接对象
的方法的时候都会进行驱动的加载
我们把这种只需要处理一次的代码块
放到了静态代码块
中
可以提高性能,减少没有必要的计算机的操作
代码如下:
import java.sql.*;
public class DbHelper {
// 关闭所有资源,可关的资源有连接对象,执行者对象,结果集对象
public static void closeAll(Connection connection, Statement statement, ResultSet resultSet){
// 按顺序来关,防止空指针异常
// 关闭结果集
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();
}
}
}
// 静态代码块
static {
// 加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// 获取连接对象,静态方法
public static Connection getConn() {
// 返回连接对象
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbhui", "root", "root123");
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return conn;
}
}