1.C3P0数据源的使用
C3P0是一个开源的JDBC连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展。C3P0有自己的格式文件,如下
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///day05</property> <property name="user">root</property> <property name="password">root</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> |
- 导jar包:
- 建立c3p0连接
package com.beiwo.day05.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class C3P0Util { //C3P0数据源 private static ComboPooledDataSource dataSource=new ComboPooledDataSource(); public static DataSource getDataSource() { return dataSource; } public static Connection getConn(){ try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } } public static Connection getConn2(){ Connection conn=null; try { conn=dataSource.getConnection(); } catch (Exception e) { e.printStackTrace(); } return conn; } //释放连接 public static void realease(ResultSet rs,Statement stmt,Connection conn){ try { if(null!=rs){ rs.close(); } } catch (Exception e) { // TODO: handle exception } try { if(null!=stmt){ stmt.close(); } } catch (Exception e) { // TODO: handle exception } try { if(null!=conn){ conn.close(); } } catch (Exception e) { // TODO: handle exception } } }
測試C3P0的使用
package com.beiwo.day05.test; import java.sql.Connection; import org.junit.Test; import com.beiwo.day05.util.C3P0Util; public class TestC3P0 { @Test public void testC3P0(){ Connection connection = C3P0Util.getConn(); System.out.println(connection.getClass().getName()); C3P0Util.realease(null, null, connection); } }