C3P0连接池

4.1使用
1.导包:c3p0-0.9.1.2.jar
2.在类路径下增加xml配置文件:c3p0-config.xml





com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/day13
root
123
10
30
100
10



3.编写工具类

public class C3P0Util {
//得到一个数据源
private static DataSource dataSource = new ComboPooledDataSource();

//从数据源中得到一个连接对象
public static Connection getConnection(){
try {
        return dataSource.getConnection();
    } catch (SQLException e) {
        throw new RuntimeException("服务器错误");
    }
}
public static void release(Connection conn,Statement stmt,ResultSet rs){
    //关闭资源
    if(rs!=null){
      try {
        rs.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      rs = null;
    }
    if(stmt!=null){
      try {
        stmt.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
      stmt = null;
    }
    if(conn!=null){
      try {
        conn.close();  //关闭,其实是交还给池子来处理
      } catch (Exception e) {
        e.printStackTrace();
      }
      conn = null;
    }
}
}

4.测试

public void testInsert(){
    Connection conn = null;
    PreparedStatement ps = null;
    
    try {
        conn = C3P0Util.getConnection();
        ps = conn.prepareStatement("insert into account(name,money) values('ggg',2000)");
        ps.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        C3P0Util.release(conn, ps, null);
        
    }
    System.out.println(conn.getClass().getName());
}

你可能感兴趣的:(C3P0连接池)