jdbc · 2019-09-11 0

JDBC配置C3P0数据库连接池(三种方式)

添加maven依赖

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.15</version>
</dependency>

<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.4</version>
</dependency>

一、set属性配置

    public void testC3P0() throws Exception {
        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql://localhost:3306/jdbc_test?serverTimezone=GMT%2B8");
        cpds.setUser("root");
        cpds.setPassword("root123");

        Connection conn = cpds.getConnection();
        System.out.println(conn);

//        并不是真正的关闭,而是归还给数据库连接池
        conn.close();
    }

二、xml配置

在类路径下新建c3p0-config-xml

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

    <named-config name="helloc3p0">

        <!--指定连接数据源的基本配置-->
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql://localhost:3306/jdbc_test?serverTimezone=GMT%2B8</property>
        <property name="user">root</property>
        <property name="password">root123</property>

        <!--若数据库中连接数不足时,一次向数据库服务器申请多少个连接-->
        <property name="acquireIncrement">5</property>
        <!--初始化数据库连接池连接的数量-->
        <property name="initialPoolSize">5</property>
        <!--数据库连接池的最小的数据库连接数-->
        <property name="minPoolSize">5</property>
        <!--数据库连接池的最大的数据库连接数-->
        <property name="maxPoolSize">10</property>

        <!--数据库连接池可以维护的statement的个数-->
        <property name="maxStatements">20</property>
        <!--每个连接同时可以使用的statement对象的个数-->
        <property name="maxStatementsPerConnection">5</property>

    </named-config>

</c3p0-config>

使用:

    public void testC3P0WithXML() throws Exception {
        DataSource dataSource = new ComboPooledDataSource("helloc3p0");

        Connection conn = dataSource.getConnection();
        System.out.println(conn);

        conn.close();
    }

三、properties配置

在类路径下新建c3p0.properties

c3p0.driverClass=com.mysql.jdbc.Driver
c3p0.jdbcUrl=jdbc:mysql://localhost:3306/jdbc_test?serverTimezone=GMT%2B8
c3p0.user=root
c3p0.password=root123

c3p0.acquireIncrement=5
c3p0.initialPoolSize=5
c3p0.minPoolSize=5
c3p0.maxPoolSize=10

c3p0.maxStatements=20
c3p0.maxStatementsPerConnection=5

使用:

    public void testC3P0WithProp() throws Exception {
        DataSource dataSource = new ComboPooledDataSource();
        Connection conn = dataSource.getConnection();
        System.out.println(conn);

        conn.close();
    }