c3p0--Jdbc连接池的基本使用

时间:2022-04-14 23:20:42

上图:
c3p0--Jdbc连接池的基本使用
要使用连接池通过配置文件读取连接信息的话,文件名必须为 c3p0-config.xml,目的是使得连接池自动通过配置自动进行连接。

当然 也可以在配置文件中设置 最小连接数和最大连接数,这里就不设置了,需要的可以在官方文档中进行查看。
配置文件大致如下:

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="user">sa</property>
<property name="password">123456</property>
<property name="driverClass">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="jdbcUrl">jdbc:sqlserver://localhost:1433;DatabaseName=estore_system</property>
</default-config> <!-- This app is massive! -->
</c3p0-config>

测试Junit类:

package com.mystore.c3p0;

import java.sql.Connection;
import java.sql.PreparedStatement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import com.mystore.utils.JdbcUtils;

/*
* 对c3p0连接池的测试使用
* 核心类ComboPoolleadDataSource
*/

public class c3p0Test{

//测试
@Test
public void test1(){
Connection connection= null;
PreparedStatement stmt = null;
String strsql = "update users set passward='1234' where userName=?";
//当使用ComboPooledDataSource的时候,会自动找到 c3p0-config.xml文件 读取里面的配置文件信息
ComboPooledDataSource cpds = new ComboPooledDataSource();
try {
//获得连接
connection = cpds.getConnection();
//预处理
stmt = connection.prepareStatement(strsql);
//给占位符 设置
stmt.setString(1, "huhongda");
//执行更新
stmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally{
//连接池会在 con关闭的时候 进行回收
JdbcUtils.release(null, stmt, connection);
}

}
}

将习得记录,方便回顾。