C3P0的使用步骤
下载C3P0的jar
包:
IDEA
中导入C3P0jar
包:
-
File--->Project Structure--->Dependencies--->"+"--->选择C3P0的jar文件
查看说明文档:
C3P0的src
目录下的doc
目录下的index.html
文件
C3P0的具体使用方法
配置c3p0-config.xml
文件
<?xml version="1.0" encoding="UTF-8" ?>
<c3p0-config>
<!-- This app is massive! -->
<!-- 自定义的配置-->
<named-config name="helloC3P0">
<!--
提供获取链接的四个基本信息
-->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///test</property>
<property name="user">junkingboy</property>
<property name="password">junkingboy</property>
<!--
进行数据库连接池管理的基本信息
-->
<!-- 当数据库连接池中的连接数不够时,c3p0一次性向数据库服务器申请的连接数 -->
<property name="acquireIncrement">5</property>
<!-- c3p0数据库连接池中初始化时的连接数 -->
<property name="initialPoolSize">100</property>
<!-- c3p0连接池中维护的最少的连接数 -->
<property name="minPoolSize">10</property>
<!-- c3p0数据库连接池当中维护的最多的连接数 -->
<!-- 超过100个连接访问的时候进行等待 -->
<property name="maxPoolSize">100</property>
<!-- intergalactoApp adopts a different approach to configuring statement caching -->
<!-- c3p0数据库连接池当中最多维护的statement的个数 -->
<property name="maxStatements">50</property>
<!-- 每一个连接可以使用的最多的statement的个数 -->
<property name="maxStatementsPerConnection">2</property>
</named-config>
</c3p0-config>
调用c3p0
数据库连接池:
方式一:硬编码方式记录数据
//方式一:硬编码方式记录数据
@Test
public void testGetConnection() throws Exception {
ComboPooledDataSource cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver"); //加载jdbc驱动--->com.mysql.jdbc.Driver
cpds.setJdbcUrl("jdbc:mysql://localhost:3306/test");
cpds.setUser("junkingboy");
cpds.setPassword("junkingboy");
//通过设置相关的参数对数据库连接池进行管理--->相关的属性可以再index.html进行查看
//通过方法设置初始的连接值当中的连接数
cpds.setInitialPoolSize(10);
Connection conn = cpds.getConnection();
System.out.println(conn);
//销毁c3p0造的连接池
DataSources.destroy(cpds);
}
方式二:使用.xml
配置文件
//方式二:使用配置文件进行c3p0数据库连接池的调用
@Test
public void testGetConnection1() throws SQLException {
//调用自己给配置起的名
ComboPooledDataSource cpds = new ComboPooledDataSource("helloC3P0");
//使用cpds获取链接,
Connection conn = cpds.getConnection();
System.out.println(conn);
}