JDBC连接池使用方法(DBCP和C3P0)

本文介绍C3P0和DBCP两种数据库连接池的配置方法及使用方式,包括导入所需jar包、配置文件的具体参数设置,以及通过工具类获取数据库连接的过程。

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

一、C3P0

  1. 导入jar包(c3p0-0.9.1.2.jar)

  2. 配置c3p0-config.xml(名称固定)

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>

    <default-config>
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3307/user?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=Hongkong</property>
        <property name="user">root</property>
        <property name="password">123456</property>
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">20</property>
    </default-config>

    <named-config name="xf">
        <property name="driverClass">com.mysql.cj.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3307/user?useUnicode=true&amp;characterEncoding=utf8&amp;useSSL=false&amp;serverTimezone=Hongkong</property>
        <property name="user">root</property>
        <property name="password">123456</property>
    </named-config>


</c3p0-config>

注意:配置jdbcuUrl时用&amp替代&
3. 编写工具类C3P0

public class C3P0Utils {
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource("xf");

    public static ComboPooledDataSource getDataSource() {
        return dataSource;
    }
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

二、DBCP

  1. 导入jar包(commons-dbcp-1.4.jar和commons-pool-1.5.6.jar)
  2. 配置db.properties
    如何设置参考http://commons.apache.org/proper/commons-dbcp/configuration.html
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3307/user
connectionProperties=useUnicode=true;characterEncoding=utf8;useSSL=false;serverTimezone=Hongkong
username=root
password=123456
  1. 编写工具类
public class DBCPUtils {
    private static DataSource dataSource;
    static {
        ClassLoader classLoader = DBCPUtils.class.getClassLoader();
        InputStream is = classLoader.getResourceAsStream("db.properties");
        Properties props = new Properties();
        try {
            props.load(is);
            dataSource = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    public static DataSource getDataSource() {
        return dataSource;
    }
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值