c3p0的基本连接配置文件 c3p0-config.xml
<c3p0-config><default-config><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql:///mybase</property><property name="user">root</property><property name="password">123456</property><property name="initialPoolSize">5</property><property name="maxPoolSize">20</property></default-config><named-config name="another"><property name="driverClass">com.mysql.jdbc.Driver</property><property name="jdbcUrl">jdbc:mysql:///mybase</property><property name="user">root</property><property name="password">123456</property></named-config></c3p0-config>
c3p0工具类
package cn.cc.jdbc.utls;import java.sql.Connection; import java.sql.SQLException;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;public class C3P0Utils {private static ComboPooledDataSource dataSource=new ComboPooledDataSource();public static DataSource getDataSource(){return dataSource;}public static Connection getConnection(){try{return dataSource.getConnection();}catch (SQLException e){throw new RuntimeException(e);}} }
测试类
public class TestC3p0 {@Testpublic void testAddUser1(){Connection conn=null;PreparedStatement ps=null;try{//2.从池子中获取连接conn=C3P0Utils.getConnection();String sql="insert into tbl_user values(null,?,?)";//3.必须在自定义的connection实现类中重写preparedStatement方法ps=conn.prepareStatement(sql);ps.setString(1, "吕布3");ps.setString(2, "貂蝉3");int rows=ps.executeUpdate();if(rows>0){System.out.println("添加成功");}else{System.out.println("添加失败");}}catch (Exception e){throw new RuntimeException(e);}finally {JDBCUtils_v3.release(conn, ps, null);}}}