jdbc----提取公共类

该博客介绍了如何创建一个Java工具类`JdbcUtils`,用于管理与数据库的连接。类中静态代码块加载了`db.properties`配置文件,获取数据库连接所需的驱动、URL、用户名和密码。通过`Class.forName()`加载驱动,`getConnection()`方法用于获取连接,而`release()`方法则用于关闭资源。这个工具类简化了数据库操作中的连接管理和资源释放。
摘要由CSDN通过智能技术生成
package com.utils;

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

public class JdbcUtils {
    private static String driver = null;
    private static String url = null;
    private static String username = null;
    private static String password = null;


    /**
     * 工具类中的的构造方法都是私有的,
     * 因为工具类中的方法都是静态的,不需要new,直接采用类名调用
     */
    private JdbcUtils(){}

    static { //静态代码块,类一加载就存在,并且只执行一次
        try {
            /*加载db.properties文件信息*/
            InputStream inputStream = JdbcUtils.class.getClassLoader().getResourceAsStream("db.properties");
            Properties properties = new Properties();
            properties.load(inputStream);

            /*获取对应的值*/
             driver = properties.getProperty("driver");
             url = properties.getProperty("url");
             username = properties.getProperty("username");
             password = properties.getProperty("password");

             /*加载驱动*/
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public  static Connection getConnection() throws Exception{
        return DriverManager.getConnection(url,username,password);
    }
    //释放链接
    public static void release(Connection connection, Statement statement, ResultSet resultSet) throws Exception{
        if (connection!=null){
            connection.close();
        }
        if (statement!=null){
            statement.close();
        }
        if (resultSet!=null){
            resultSet.close();
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值