数据库连接池
数据库连接池是管理并发访问数据库连接的理想解决方案
DriverManager管理数据库连接适合单线程情况;而在多线程并发情况下,为了能够重用数据库连接,同时控制并发连接总数,保护数据库避免连接过载,所以一定要使用数据库。
//创建连接池对象
BasicDataSource ds = new BasicDataSource();
//设置必须的参数
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
//设置连接池的管理策略参数
ds.setInitialSize(2);
ds.setMaxActive(100);
//使用连接池中的数据库连接
Connection conn = ds.getConnection();
//执行SQL
String sql = "select 'hello' as a from dual ";
Statement st = conn.createStaatement();
ResultSet rs = st.execute(sql);
while(rs.nexxt()){
String str = rs.getString('a');
system.out.println(str);
}
//归还连接到数据库连接池!!
conn.close();
为了便捷的使用连接池,经常要将连接池封装为一个连接管理工具类:
/**
* 连接池版本的 数据库 连接管理工具类
* 适合于并发场合
*/
public clss DBUtils {
private static String driver;
private static String url;
private static String username;
private static String password;
private static int initSize;
private static int maxSize;
private static BasicDataSource ds;
static{
ds = new BasicDataSource();
Properties cfg = new Properties();
try{
InputStream in = DBUtils.class.getClassLoader().getResourceAsStream("db.properties");
cfg.load(in);
//初始化参数
driver = cfg.getProperty("jdbc.driver");
url = cfg.getProperty("jdbc.url");
username = cfg.getProperty("jdbc.username");
password = cfg.getProperty("jdbc.password");
initSize = Integer.parseInt(cfg.getProperty("initSize"));
maxActive = Integer.parseInt(cfg.getProperty("maxActive"));
in.close();
}
}
测试类
public class Demo {
public static void main(String[] args){
Connection conn = null;
try{
conn = DBUtils.getConnection();
String sql = "select 'hello' as a fom dual";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(sql);
while(rs.nexxt()){
String str = rs.getString('a');
system.out.println(str);
}
rs.close;
st.close;
}