封装一个1.获取connection对象2.关闭资源工具类

public class JdbcUtil {
    private static String url = null;
    private static String user =null;
    private static String password = null;
    static {
        try {
        //只要JdbcUtil类加载了,就会执行静态代码块中的代码
        //读取配置文件中的信息:properties文件
        //Properties类表示一组持久的属性。 Properties可以保存到流中或从流中加载。
        // 属性列表中的每个键及其对应的值都是一个字符串。
            Properties properties = new Properties();
            properties.load(new FileInputStream("src/db.properties"));
            //数据都在properties 对象中
            String diver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            Class.forName(diver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection () {

        Connection connection = null;
        try {
            connection = DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return  connection;
    }

    //关闭资源
    //增删改  需要关闭两个   查 关闭三个
    public static void close (Connection connection) {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void close (Statement statement, Connection connection) {
        try {
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    public static void close (ResultSet resultSet, Statement statement, Connection connection) {
        try {
            resultSet.close();
            statement.close();
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值