Java实现C3P0数据库连接池
maven 下载依赖包
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<!-- https://mvnrepository.com/artifact/c3p0/c3p0 -->
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
创建c3p0-config.xml 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--默认配置-->
<default-config>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</default-config>
<!--配置连接池mysql-->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://192.168.146.222:3306/school</property>
<property name="user">root</property>
<property name="password">1</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
<!--配置连接池2-->
......
<!--配置连接池3-->
......
<!--配置连接池4-->
......
</c3p0-config>
实现代码
这里需要注意的地方是,ComboPooledDataSource(“mysql”); 里面写的名称需要和 xml配置文件内 named-config name=“mysql” 保持一致,否则无法调用成功。
public class C3P0Utils {
//通过标识名来创建相应连接池
static ComboPooledDataSource dataSource=new ComboPooledDataSource("mysql");
//从连接池中取用一个连接
public static Connection getConnection(){
Connection connection =null;
try {
connection = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return connection;
}
public static void main(String[] args) {
Connection connection1 = C3P0Utils.getConnection();
Connection connection2 = C3P0Utils.getConnection();
if (connection1==connection2){
System.out.println("true");
}else {
System.out.println("false");
}
try {
connection1.close();
connection2.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
//释放资源
public static void close(Connection conn, PreparedStatement pstmt, ResultSet rs){
if (rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt!=null){
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}