c3p0的基本连接配置文件 c3p0-config.xml
com.mysql.jdbc.Driver jdbc:mysql:///mybase root 123456 5 20 com.mysql.jdbc.Driver jdbc:mysql:///mybase root 123456
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 { @Test public 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); } } }