连接池 ----单例模式
//数据库连接池 单例模式 import java.sql.Connection; import java.sql.SQLException; import com.mchange.v2.c3p0.ComboPooledDataSource; import com.mchange.v2.c3p0.DataSources; public class ComboPooledDataSourceDemo { private static ComboPooledDataSourceDemo instance; private ComboPooledDataSource ds; private ComboPooledDataSourceDemo() throws Exception { ds = new ComboPooledDataSource(); ds.setDriverClass("oracle.jdbc.driver.OracleDriver"); //驱动 ds.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:orcl"); //地址 ds.setUser("test0816"); //数据库用户名 ds.setPassword("934617699"); //数据库用户密码 //初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 5 initialPoolSize ds.setInitialPoolSize(5); //连接池中保留的最大连接数。Default: 20 maxPoolSize ds.setMaxPoolSize(20); //// 连接池中保留的最小连接数。 //ds.setMinPoolSize(1); //当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 5 acquireIncrement ds.setAcquireIncrement(10); //用来返回该对象 public static final ComboPooledDataSourceDemo getInstance() { if (instance == null) { try { instance = new ComboPooledDataSourceDemo(); } catch (Exception e) { e.printStackTrace(); } } return instance; } //返回一个连接 public synchronized final Connection getConnection() { try { return ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return null; } }
package com.phone.shuyinghengxie; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.junit.Test; public class ComboPooledDataSourceDemoTest1 { public static void main(String[] args) { ComboPooledDataSourceDemo cp = ComboPooledDataSourceDemo.getInstance() ; List<Person> list = new ArrayList<>() ; cp.getConnection() ; String sql = "select * from person " ; try { PreparedStatement pt = cp.getConnection().prepareStatement(sql) ; ResultSet rt = pt.executeQuery() ; while(rt.next()) { Person p = new Person(); p.setName(rt.getString("name")); p.setAge(rt.getString("age")); p.setSex(rt.getString("sex")); p.setTelNum(rt.getString("telNum")); p.setAddress(rt.getString("address")); list.add(p) ; } for(Person p : list) { System.out.println(p); } System.out.println("哈哈"); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } }