JDBCUtils工具类的书写

9 篇文章 0 订阅
package jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    public static String driver;
    public static String url;
    public static String user;
    public static String password;
    // 利用静态初始化块进行初始化操作
    static { // 静态初始化块在类加载时执行
        try (
                // 1. 通过类加载器读取配置文件
                // 1.1 通过类加载器获取配置文件的输入流
                InputStream is = JDBCUtils.class.getClassLoader()
                        .getResourceAsStream("db.propeties");
        ) {
            // 1.2 创建 Properties 对象
            Properties prop = new Properties();
            // 1.3 加载“配置文件”输入流
            prop.load(is);
            // 2. 执行初始化操作
            driver = prop.getProperty("driver");
            url = prop.getProperty("url");
            user = prop.getProperty("user");
            password = prop.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 3. 加载 MySQL 数据库驱动
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    // 获取数据库连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
    // 释放 Connection、Statement 和 ResultSet 资源
    // 这里也可以不写释放资源的两个方法,直接使用try-with-resource语句释放资源
    // 将Connection、Statement 和 ResultSet 对象的创建放在 try 后面的小(圆)括号中
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) throws SQLException {
        if (rs != null) {
            rs.close();
        }
        // 在方法体中调用本类的另一个方法时,可以省略写 this
        close(conn, stmt);
    }
    // 重载 close 方法
    public static void close(Connection conn, Statement stmt) throws SQLException {
        if (conn != null) {
            conn.close();
        }
        if (stmt != null) {
            stmt.close();
        }
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值