概述

C3P0是一个开源的数据库连接池,它实现了数据源与JNDI绑定,支持JDBC3规范和实现了JDBC2的标准扩展说明的Connection和Statement池的DataSources对象。

即将用于连接数据库的连接整合在一起形成一个随取随用的数据库连接池

DataSource

数据源。为了提高系统性能,在真实的Java项目中通过不会使用原生的JDBC的DriverManager去连接数据库,而是使用数据源(java.sql.DataSource)来代替DriverManager管理数据库的连接。

其中C3P0就是一种常见的数据源,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个。它提供了高效管理和复用数据库连接的功能。

使用

通过代码

ComboPooledDataSource source = new ComboPooledDataSource();

source.setDriverClass("com.mysql.jdbc.Driver");
source.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/mysql");
source.setUser("root");
source.setPassword("root");

Connection connection = source.getConnection();

通过配置文件

c3p0-config.xml

<c3p0-config>
    <!-- 默认配置,如果没有指定则使用这个配置 -->
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">
            <![CDATA[jdbc:mysql://127.0.0.1:3306/mysql]]>
        </property>
        <property name="user">root</property>
        <property name="password">root</property>
        <!-- 初始化池大小 -->
        <property name="initialPoolSize">2</property>
        <!-- 最大空闲时间 -->
        <property name="maxIdleTime">30</property>
        <!-- 最多有多少个连接 -->
        <property name="maxPoolSize">10</property>
        <!-- 最少几个连接 -->
        <property name="minPoolSize">2</property>
        <!-- 每次最多可以执行多少个批处理语句 -->
        <property name="maxStatements">50</property>
    </default-config>
</c3p0-config>

只需实例化对象即可

ComboPooledDataSource source = new ComboPooledDataSource();

Connection connection = source.getConnection();

环境

com.mchange:c3p0:0.9.5.2

com.mchange:mchange-commons-java:0.2.11

URLClassLoader

调用链

com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase#readObject
↓
ReferenceIndirector$ReferenceSerialized#getObject
↓
ReferenceableUtils.referenceToObject