【druid + MySQL】〖代码〗JDBCUtils使用druid数据库连接池工具类

博客主要提及了JDBCUtils使用druid数据库连接池工具类的相关代码内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

〖代码〗JDBCUtils使用druid数据库连接池工具类

package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.*;
import java.util.Properties;

public class JdbcUtils {

    private static DataSource ds; // 数据源

    /*
     * 读取JDBC配置文件(写在静态代码块中,这样读取只进行一次)
     */
    static {
        // 1.创建Properties集合类
        Properties pro = new Properties();
        try {
            // 2.通过反射机制读取配置文件
            pro.load(JdbcUtils.class.getClassLoader().getResourceAsStream("properties/druid.properties"));
            // 3.获取DataSource
            ds = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /*
     * 获取连接池
     */
    public static DataSource getDataSource() throws SQLException {
        return ds;
    }

    /*
     * 获取连接
     */
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }

    /*
     * 关闭连接
     */
    public static void close(ResultSet rs, PreparedStatement pst, Connection con) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        if (con != null) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }
    public static void close(Connection con) {
        if (con != null) {
            try {
                con.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
    }

}


我寻见一片海 碧蓝且耀着光
大片船只航行其上 都向着远方

                         Shared by Foriver_江河



© 1997-8023 江河 All Rights Reserved.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值