目录
1.下载包c3p0的jar包,因我之前就有所以就用这个c3p0-0.9.2.1.jar,并引入到你的项目中。
2.在src下放入xml配置:c3p0-config.xml
1.下载包c3p0的jar包,因我之前就有所以就用这个c3p0-0.9.2.1.jar,并引入到你的项目中。
2.在src下放入xml配置:c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!--
C3P0的缺省(默认)配置,
如果在代码中“ComboPooledDataSource ds = new ComboPooledDataSource();”这样写就表示使用的是C3P0的缺省(默认)配置信息来创建数据源
-->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
<!--
C3P0的命名配置,
如果在代码中“ComboPooledDataSource ds = new ComboPooledDataSource("MySQL");”这样写就表示使用的是name是MySQL的配置信息来创建数据源
-->
<named-config name="MySQL">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/test</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
</c3p0-config>
3.编写工具类:
package com.yszd;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3P0_Utils {
private static ComboPooledDataSource dataSource = null;
//在静态代码块中创建数据库连接池
static{
try{
dataSource = new ComboPooledDataSource("MySQL");//使用C3P0的命名配置来创建数据源
}catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
public static Connection getConnection() throws SQLException{
//从数据源中获取数据库连接
return dataSource.getConnection();
}
// 释放资源
public static void release(Connection conn,Statement st,ResultSet rs){
if(rs!=null){
try{
//关闭存储查询结果的ResultSet对象
rs.close();
}catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if(st!=null){
try{
//关闭负责执行SQL命令的Statement对象
st.close();
}catch (Exception e) {
e.printStackTrace();
}
}
if(conn!=null){
try{
//将Connection连接对象还给数据库连接池
conn.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
4.编写测试类:
package com.yszd;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DataSourceTest {
public void c3p0DataSourceTest() {
Connection conn = null;
PreparedStatement st = null;
ResultSet rs = null;
try{
//获取数据库连接
conn = C3P0_Utils.getConnection();
//插入语句
String sql = "insert into test(id,name) values(?,?)";
st = conn.prepareStatement(sql);
st.setInt(1, 1);
st.setString(2, "test");
st.executeUpdate();
}catch (Exception e) {
e.printStackTrace();
}finally{
//释放资源
C3P0_Utils.release(conn, st, rs);
}
}
public static void main(String[] args) {
new DataSourceTest().c3p0DataSourceTest();
}
}