JDBC连接池C3P0(一)(使用properties文件进行配置)

【JDBC连接池C3P0(一)(使用properties文件进行配置)】1、在src下新建一个properties文件,名字随便符合命名规范即可,我这里的名称为:c3p0config.properties,内容如下:

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/test jdbc.username=root jdbc.pwd=root

2、新建类进行连接测试:
public class DBConnectionByC3P0 { private static String url = null; private static String username = null; private static String pwd = null; private static DataSource ds_pooled; //私有构造方法,不能创建对象 private DBConnectionByC3P0(){ } //加载数据库连接的配置文件和驱动 static{ Properties env = new Properties(); try { InputStream in = DBConnectionByC3P0.class.getResourceAsStream("/c3p0config.properties"); //加载属性文件中的数据库配置信息 //以=左边作为key值,右边作为value值 env.load(in); //1. 加载驱动类 Class.forName(env.getProperty("jdbc.driver")); url = env.getProperty("jdbc.url"); username = env.getProperty("jdbc.username"); pwd = env.getProperty("jdbc.pwd"); //2、设置连接数据库的配置信息 DataSource ds_unpooled = DataSources.unpooledDataSource(url, username, pwd); Map pool_conf = new HashMap(); //3、设置最大连接数 pool_conf.put("maxPoolSize", 10); ds_pooled = DataSources.pooledDataSource(ds_unpooled,pool_conf); } catch (Exception e) { e.printStackTrace(); } } //获取连接对象 public static Connection getConnection() throws SQLException { return ds_pooled.getConnection(); } //释放连接池资源 public static void clearup(){ if(ds_pooled != null){ try { DataSources.destroy(ds_pooled); } catch (SQLException e) { e.printStackTrace(); } } } private static Integer counter = 0; public static void main(String[] args){ for (int i = 1; i <= 20; i++) { new Thread(new Runnable() { public void run() { Connection conn = null; try { conn = DBConnectionByC3P0.getConnection(); synchronized (counter) { System.out.print(Thread.currentThread().getName()); System.out.print("counter=" +(counter++)+ "\tconn="+conn); System.out.println(); conn.prepareStatement("select * from s_user"); conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }).start(); } } }


    推荐阅读