JDBC-03-抽取工具类JDBCUtils

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();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值