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);}}}
?