数据库连接池之ComboPooledDataSource

数据库的连接池有很多,今天来学习一下ComboPooledDataSource;

需要的jar包:

<dependency>
    <groupId>c3p0groupId>
    <artifactId>c3p0artifactId>
    <version>0.9.1.2version>
dependency>

因为是mysql数据库,所以还需要

<dependency>
    <groupId>mysqlgroupId>
    <artifactId>mysql-connector-javaartifactId>
    <version>5.1.34version>
dependency>

第一种方式:不采用配置文件配置,纯java代码连接:

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Connection;


public class TestCombo{
    private ComboPooledDataSource dataSource;
    private TestCombo() {
        try {
            dataSource = new ComboPooledDataSource();
            dataSource.setUser(root);
            dataSource.setPassword(123456);
            dataSource.setJdbcUrl(jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8");
            dataSource.setDriverClass(com.mysql.jdbc.Driver);
            dataSource.setInitialPoolSize();
            dataSource.setAcquireIncrement();
            dataSource.setMinPoolSize();
            dataSource.setMaxPoolSize();
            dataSource.setMaxStatements();
            dataSource.setMaxIdleTime();
            dataSource.setIdleConnectionTestPeriod();
            dataSource.setAcquireRetryAttempts();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

  
    public Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (Exception e) {
            throw new RuntimeException("can not get sms database connection  ", e);
        }
    }

}
第二种方式(配置文件)

配置文件:c3p0-config.xml 

名字必须为这个!

<c3p0-config>

   <default-config>

<property name="driverClass">com.mysql.jdbc.Driverproperty>

<property name="jdbcUrl">

property>

<property name="user">rootproperty>

<property name="password">1234property>

<property name="initialPoolSize">2property>

<property name="maxIdleTime">30property>

<property name="maxPoolSize">10property>

<property name="minPoolSize">2property>

<property name="maxStatements">50property>

default-config>

<named-config name="demo">

<property name="driverClass">com.mysql.jdbc.Driverproperty>

<property name="jdbcUrl">property>

<property name="user">rootproperty>

<property name="password">1234property>

<property name="acquireIncrement">5property>

<property name="initialPoolSize">100property>

<property name="minPoolSize">50property>

<property name="maxPoolSize">1000property>

<property name="maxStatements">0property>

<property name="maxStatementsPerConnection">5property>

named-config>

c3p0-config>

代码中获取实例

ComboPooledDataSource pool = new ComboPooledDataSource();//空参,自动到classpath目录下面加载“c3p0-config.xml”配置文件---配置文件的存储位置和名称必须是这样,且使用“默认配置”

ComboPooledDataSource pool = new ComboPooledDataSource("demo");//加载“c3p0-config.xml”文件中定义的“demo”这个配置元素

你可能感兴趣的:(数据库mysql)