C3P0连接池
C3p0-config.xml配置文件 放在src根目录下
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config>
<default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://服务器ip:3306/Web08</property> <property name="user">root</property> <property name="password">密码</property> <property name="initialPoolSize">5</property> <property name="maxPoolSize">20</property> </default-config>
<named-config name="oracle"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///web_07</property> <property name="user">root</property> <property name="password">123</property> </named-config>
</c3p0-config> |
C3p0实现代码
package cn.itcast.C3P0;
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException;
import org.junit.Test; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Demo { @Test public void C3P0Utlis() throws Exception { Connection con = null; PreparedStatement pstam = null; //调用ComboPooledDataSource()会自动加载并读取c3p0-config.xml文件 ComboPooledDataSource dataSource = new ComboPooledDataSource();//掉用default的xml配置选项 //ComboPooledDataSource dataSource = new ComboPooledDataSource("oracle");//掉用 <named-config name="oracle"> 的xml配置选项 con = dataSource.getConnection(); String sql = "insert into product values(?,?,?,null,null);"; pstam = con.prepareStatement(sql); pstam.setObject(1, "p020"); pstam.setObject(2, "bye"); pstam.setObject(3, 30.3); int row = pstam.executeUpdate(); if(row>0) { System.out.println("添加成功"); }else { System.out.println("添加失败"); } pstam.close(); con.close(); } } |