标签:
注意事项:配置文件规定命名,不能更改 c3p0-config
<?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/day16</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</default-config>
</c3p0-config>
c3p0数据连接池
package com.itheima.utils; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Util { private static DataSource ds =new ComboPooledDataSource(); /** * 用于从池中获取连接 * @return */ public static synchronized Connection getConneciton(){ try { return ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } //关闭资源 public static void release(ResultSet rs,Statement st,Connection con ){ try { if(rs!=null){ rs.close(); rs=null;//目的是让回收器立即进行垃圾回收 } } catch (SQLException e) { e.printStackTrace(); } try { if(st!=null){ st.close(); st=null; } } catch (SQLException e) { e.printStackTrace(); } try { if(con!=null){ con.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
测试程序
package com.itheima.test; import java.sql.Connection; import java.sql.Statement; import com.itheima.utils.C3P0Util; public class C3P0Test { /** * @param args */ public static void main(String[] args) { Connection con = null; Statement st = null; try { con =C3P0Util.getConneciton(); //..... st = con.createStatement(); st.executeUpdate("insert into account values(5,‘cgx‘,100)"); } catch (Exception e) { e.printStackTrace(); }finally{ C3P0Util.release(null, st, con); } } }
标签:
原文地址:http://www.cnblogs.com/baijin05/p/5075003.html