@Test public void testPool() throws Exception{ BasicDataSource ds = new BasicDataSource(); //设置driver ds.setDriverClassName("com.mysql.jdbc.Driver"); //设置url ds.setUrl("jdbc:mysql:///db909?characterEncoding=utf8"); ds.setUsername("root"); ds.setPassword("123456"); ds.setInitialSize(2);//设置在开始时创建几个链接 ds.setMaxActive(5);//设置最多有几个链接 //下面两个很少用 ds.setDefaultAutoCommit(true);//设置所有连接是否自动提交(默认) ds.setMaxIdle(3000);//设置每个连接最大的空闲时间 Connection conn = ds.getConnection(); Connection conn2 = ds.getConnection(); Connection conn3 = ds.getConnection(); Connection conn4 = ds.getConnection(); Connection conn5 = ds.getConnection(); System.out.println("c1"+conn.hashCode()+","+conn.getClass()); System.out.println("c2"+conn2.hashCode()); System.out.println("c3"+conn3.hashCode()); System.out.println("c4"+conn4.hashCode()); System.out.println("c5"+conn5.hashCode()); conn.close(); Connection conn6 = ds.getConnection(); System.out.println("c6"+conn6.hashCode()); }
输出
c1956723359,class org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
c21439429624c31090407113c41994388340c51760068004c6956723359/* * 通过配置文件创建连接 */ @Test public void testPool2() throws Exception { Properties p = new Properties(); p.load(DbcpPool.class.getResourceAsStream("jdbc.properties")); DataSource ds = new BasicDataSourceFactory().createDataSource(p); Connection c1 = ds.getConnection(); Connection c2 = ds.getConnection(); Connection c3 = ds.getConnection(); System.out.println(c1.hashCode()+","+c1.getClass()); System.out.println(c2.hashCode()+","+c2.getClass()); System.out.println(c3.hashCode()+","+c3.getClass()); c3.close(); Connection c4 = ds.getConnection(); System.out.println(c4.hashCode()+","+c4.getClass()); }
#以下所有属性,都来自于BasicDataSource的setXxxx方法
driverClassName=com.mysql.jdbc.Driverurl=jdbc:mysql:///db909username=rootpassword=123456maxActive=3输出:
696865876,class org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
1996450841,class org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper2064783959,class org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper2064783959,class org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper
在一个项目中,就只能拥有一个DataSource的实例。在这个DataSource3中有多个Connection
声明一个工厂类,创建维护唯一的一个DataSource