-
-
Save wdfx100/5387099 to your computer and use it in GitHub Desktop.
数据库连接池
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//jar:commons-dbcp-1.4 | |
//依赖的jar:commons-pool-1.5.6 | |
//第一种// | |
private static BasicDataSource bd=null; | |
static{ | |
bd = new BasicDataSource(); | |
bd.setDriverClassName(DIRVER); | |
bd.setUrl(URL); | |
bd.setUsername(NAME); | |
bd.setPassword(PASSWORD); | |
bd.setInitialSize(5);//最初创建的连接数 | |
bd.setMaxWait(5000);//等待最大的毫秒数 | |
bd.setMaxActive(20);//活跃的连接的最大数目 | |
bd.setMinIdle(10);//最低数量的活跃的连接 | |
} | |
public Connection getConnection() { | |
Connection conn = null; | |
try { | |
conn = bd.getConnection(); | |
return conn; | |
} catch (Exception e) { | |
throw new DataAccessException("获取数据库连接异常",e); | |
} | |
} | |
// 第二种// | |
private static BasicDataSource bd = bilderDataSource(); | |
private static BasicDataSource bilderDataSource(){ | |
bd = new BasicDataSource(); | |
bd.setDriverClassName(DIRVER); | |
bd.setUrl(URL); | |
bd.setUsername(NAME); | |
bd.setPassword(PASSWORD); | |
bd.setInitialSize(5);//最初创建的连接数 | |
bd.setMaxWait(5000);//等待最大的毫秒数 | |
bd.setMaxActive(20);//活跃的连接的最大数目 | |
bd.setMinIdle(10);//最低数量的活跃的连接 | |
return bd; | |
} | |
//增加配置文件:建一个Source Folder文件,名为etc,注意在classes内的路径,引用名为:db.properties | |
private static BasicDataSource bd = bilderDataSource(); | |
private static BasicDataSource bilderDataSource(){ | |
String driver=null; | |
String url = null; | |
String name = null; | |
String password = null; | |
Properties pro = new Properties(); | |
try { | |
pro.load(DBUtil.class.getClassLoader().getResourceAsStream("db.properties")); | |
driver = pro.getProperty("driver"); | |
url = pro.getProperty("url"); | |
name = pro.getProperty("name"); | |
password = pro.getProperty("password"); | |
} catch (IOException e) { | |
throw new DataAccessException("读取数据库配置文件错误",e); | |
} | |
bd = new BasicDataSource(); | |
bd.setDriverClassName(driver); | |
bd.setUrl(url); | |
bd.setUsername(name); | |
bd.setPassword(password); | |
bd.setInitialSize(5);//最初创建的连接数 | |
bd.setMaxWait(5000);//等待最大的毫秒数 | |
bd.setMaxActive(20);//活跃的连接的最大数目 | |
bd.setMinIdle(10);//最低数量的活跃的连接 | |
return bd; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment