日期:2014-05-19 浏览次数:20770 次
import java.beans.PropertyVetoException; import java.sql.Connection; import java.sql.SQLException; import java.text.SimpleDateFormat; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.DataSources; public class TestC3P01 { /** * @param args */ public static void main(String[] args) { ComboPooledDataSource cpds = new ComboPooledDataSource(); try { cpds.setDriverClass( "com.mysql.jdbc.Driver" ); } catch (PropertyVetoException e) { e.printStackTrace(); System.exit(1); } cpds.setJdbcUrl( "jdbc:mysql://127.0.0.1:3306/test" ); cpds.setUser("hb"); cpds.setPassword("123456"); cpds.setMinPoolSize(5); cpds.setMaxPoolSize(20); cpds.setInitialPoolSize(10); cpds.setAcquireRetryAttempts(1); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Connection[] c = new Connection[20]; for(int i = 0; i < 20; i++) { try { System.out.println(df.format(new java.util.Date())); System.out.println("申请第" + i + "个数据库连接"); c[i] = cpds.getConnection(); System.out.println(df.format(new java.util.Date())); } catch (SQLException e) { System.out.println(df.format(new java.util.Date())); e.printStackTrace(); } } try { System.out.println("超过最大连接数后再次申请数据库连接"); Connection con = cpds.getConnection(); System.out.println(df.format(new java.util.Date())); } catch (Exception e) { System.out.println(df.format(new java.util.Date())); e.printStackTrace(); System.exit(1); } try { DataSources.destroy( cpds ); } catch (SQLException e) { e.printStackTrace(); } } }