package com.util;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class PoolUtil{
//创建出BasicDataSource类对象
private static BasicDataSource datasource = new BasicDataSource();
private static Properties per = new Properties();
//静态代码块,对象BasicDataSource对象中的配置,自定义
static{
try {
//in = new FileInputStream(PoolUtil.class.getClassLoader().getResourceAsStream("db.properties"));
//r.load(in);
per.load(PoolUtil.class.getClassLoader().getResourceAsStream("db.properties"));
String driver = per.getProperty("driver");
String url = per.getProperty("url");
String username = per.getProperty("username");
String password = per.getProperty("password");
Integer maxActive = Integer.parseInt(per.getProperty("maxActive"));
Integer maxWait = Integer.parseInt(per.getProperty("maxWait"));
datasource.setDriverClassName(driver);
datasource.setUrl(url);
datasource.setUsername(username);
datasource.setPassword(password);
//对象连接池中的连接数量配置,可选的
datasource.setInitialSize(10);//初始化的连接数
datasource.setMaxActive(maxActive);//最大连接数量
datasource.setMaxWait(maxWait);
datasource.setMaxIdle(5);//最大空闲数
datasource.setMinIdle(1);//最小空闲
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//定义静态方法,返回BasicDataSource类的对象
public static DataSource getDataSource(){
return datasource;
}
public static void closeConnection(Connection conn){
try {
/*
* 若该连接是通过连接池获取的,那么调用
* 这个连接的close方法并不是与数据库断开
* 连接了,而仅仅是将该连接还给连接池。
*/
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}