16.C3P0数据库连接池的使用
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/day12</property> <property name="user">root</property> <property name="password">123456</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>
C3P0Utils.java
package com.gyf.utils; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import java.util.ResourceBundle; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Utils { /** * 使用了连接池后,使用数据源来获取连接 * 数据源,也就是连接池 */ private static DataSource ds = new ComboPooledDataSource(); /* static{ ds = new ComboPooledDataSource(); }*/ public static Connection getConnection() throws SQLException{ return ds.getConnection(); } public static void close(ResultSet rs,Statement stmt,Connection conn){ if(rs != null){ try { rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(stmt !=null){ try { stmt.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(conn !=null){ try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }