package DB; import com.mchange.v2.c3p0.ComboPooledDataSource; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; /** * Created by Administrator on 2018\11\23 0023. */ public class C3p0Utils { private static DataSource dataSource=null; static{ dataSource=new ComboPooledDataSource("mysql"); } /* c3p0数据库连接 */ public static Connection getConnection(){ Connection connection = null; try{ connection = dataSource.getConnection(); }catch (Exception E){ E.printStackTrace(); } return connection; } /** * 关闭数据库连接 * */ public static void closeConn(Connection connection){ try { //如果连接不等于空 并且连接已经关闭 选择关闭连接connection if(connection!=null && connection.isClosed()){ connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
配置
<?xml version="1.0" encoding="UTF-8"?> <!-- 配置c3p0config --> <c3p0-config> <default-config> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <named-config name="mysql"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/test</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> <property name="maxStatements">200</property> </named-config> </c3p0-config>