c3p0数据库连接池(作用不重复)

/*
* c3p0数据库连接池:
* 只被初始化一次
* connection对象进行close时,不是正的关闭,而是将该数据连接归还给数据库连接池
*
* */

四个架包

mysql-connector-java-jar

commons-dbcp-1.4jar

commons-pool-1.5.5jar

c3p0-0.9.1.2.jar(在架包//其他,文件下)导进去

----------------------------------------------------------------------------------------------

//方法一
public void testC3p0() throws Exception{
ComboPooledDataSource cpds=new ComboPooledDataSource();

cpds.setDriverClass("com.mysql.jdbc.Driver");
cpds.setJdbcUrl("jdbc:mysql:///lxn");
cpds.setUser("root");
cpds.setPassword("lxn123");
System.out.println(cpds.getConnection());
}

-----------------------------------------------------------------------------------------------
//方法二:通过配置文件的方法连接数据库

首先在src目录下建立一个XML文件

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

<named-config name="helloc3p0">

<!-- 指定连接数据源的基本属性 -->
<property name="user">root</property>
<property name="password">lxn123</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///lxn</property>

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

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

</named-config>

</c3p0-config>

连接方法:
public void testC3p0WithConfigFile() throws Exception{
DataSource dataSource=new ComboPooledDataSource("helloc3po");
System.out.println(dataSource.getConnection());

ComboPooledDataSource comboPooledDataSource=(ComboPooledDataSource) dataSource;
System.out.println(comboPooledDataSource.getMaxStatements());
}

------------------------------------------------------------------------------------------------------------
//方法三:在src目录下建立一个XML文件,例上

连接测试方法:
private static DataSource dataSource=null;


static{
dataSource=new ComboPooledDataSource("helloc3p0");
}


public static Connection getConnection() throws Exception{
return dataSource.getConnection();
}


@Test
public void testC3p0L() throws Exception{
Connection connection=getConnection();
System.out.println(connection);
}

posted @ 2016-08-16 10:53  G-&-D  阅读(782)  评论(0编辑  收藏  举报