数据库连接池c3p0基本使用和配置演示
c3p0:数据库连接池技术
步骤:
导入jar包(两个) c3p0-0.9.5.2.jar mchange-commons-java-0.2.12.jar
不要忘记导入数据库驱动jar包
定制配置文件:
名称:c3p0.properties或者c390-config.xml
路径:直接将文件放在src目录下即可
创建核心对象 数据库连接池对象 ComboPooledDataSource
c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="user">root</property>
<property name="password">root</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///root</property>
</default-config><!-- This app is massive! -->
</c3p0-config>
/**
* c3p0演示
*/
public class C3P0Demo1 {
public static void main(String[] args) throws SQLException {
//创建数据库连接池对象
DataSource ds = new ComboPooledDataSource();
//获取连接对象
Connection conn = ds.getConnection();
System.out.println(conn);
}
}
package cn.itcust.datasource.c3p0;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class C3P0Demo2 {
public static void main(String[] args) throws SQLException {
//获取DataSource
DataSource ds = new ComboPooledDataSource();
//获取连接
for (int i = 0; i < 10; i++) {
Connection conn = ds.getConnection();
System.out.println(i+"-->"+conn);
}
}
}
package cn.itcust.datasource.c3p0;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
public class C3P0Demo2 {
public static void main(String[] args) throws SQLException {
//获取DataSource
DataSource ds = new ComboPooledDataSource();
//获取连接
for (int i = 0; i < 10; i++) {
Connection conn = ds.getConnection();
System.out.println(i+"-->"+conn);
if (i == 5) {
conn.close();//归还连接导连接池中
}
}
}
}