关于数据库连接池的学习

时间:2020-12-06 11:49:17

数据库连接池是Connection对象的工厂:

因为在创建数据库连接时都会打开一个物理连接,当使用完之后在关闭,会降低性能。所以就会使用到数据库连接池,在数据库连接池中我们会创建一定的连接数,当我们

要连接数据库的时候就从池子里取出以有的连接,用完之后在放回到池子中。如果当池子中的连接都被用到了。就会进行等待,如果超出了等待时间就会报异常。

对于数据库连接池。我们可以使用Apache 的BasicDataSource ,这个类主要实现了DataSource 接口。 对于使用这个类我们要放入:commons.pool.jar,commons.dbcp.jar,commons.collections.jar。

 1 package com.devil.util;
2
3 import java.sql.Connection;
4 import java.sql.SQLException;
5
6 import org.apache.commons.dbcp.BasicDataSource;
7
8 public class DataBasePool {
9
10 private static final DataBasePool instance = new DataBasePool();
11 BasicDataSource ds = new BasicDataSource();
12 private DataBasePool(){
13 ds.setPassword(XMLDateParse.getPassword());
14 ds.setUrl(XMLDateParse.getUrl());
15 ds.setUsername(XMLDateParse.getUsername());
16 ds.setDriverClassName(XMLDateParse.getDriver());
17
18 //set the max data connection pool connection active count
19 ds.setMaxActive(10);
20 //set the initial connection size
21 ds.setInitialSize(2);
22 //set the min idle size
23 ds.setMinIdle(2);
24 //set the max wait mins
25 ds.setMaxWait(2000);
26
27 }
28 public Connection getConnection(){
29
30 Connection conn = null;
31 try {
32 conn = ds.getConnection();
33 } catch (SQLException e) {
34 e.printStackTrace();
35 }
36
37 return conn;
38 }
39
40 public static DataBasePool getInstance() {
41 return instance;
42 }
43
44 public void close(){
45 try {
46 if(ds != null){
47 ds.close();
48 }
49 } catch (SQLException e) {
50 }
51 }
52 }