欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C3P0连接池

程序员文章站 2024-02-28 23:42:10
...

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


<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/day13</property>
<property name="user">root</property>
<property name="password">123</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>

</default-config>
</c3p0-config>


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