package com.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.common.Utils;
public class DBConnectPool {
private static List<Connection> conns = new LinkedList<Connection>();// 连接池
private static String driver;//数据库驱动
private static String url;//数据库链接地址
private static String userName;//数据库用户名
private static String password;//数据库密码
private static int initialSize;//数据库连接池数量
private static List<Connection> m_usedConnection = new LinkedList<Connection>();//已经使用的连接
/**
* 创建连接池
*
* @throws Exception
*/
public static void createConnectionPool() throws Exception {
driver = Utils.getStringFormProperty("driverClassName");
url = Utils.getStringFormProperty("url");
userName = Utils.getStringFormProperty("username");
password = Utils.getStringFormProperty("password");
initialSize = Integer.parseInt(Utils.getStringFormProperty("initialSize"));
Class.forName(driver);
// 创建连接池
for (int i = 0; i < initialSize; i++) {
Connection conn = DriverManager.getConnection(url, userName, password);
conns.add(conn);
}
}
/**
* 获取数据库链接
* @return
*/
public synchronized static Connection getConnection(){
Connection conn = null;
if(conns.size() > 0){
conn = conns.get(0);
conns.remove(0);
}
m_usedConnection.add(conn);
return conn;
}
/**
* 释放链接资源
* @throws Exception
*/
public static void closedConnectionPool() throws Exception{
List<Connection> list = new ArrayList<Connection>();
if(m_usedConnection.size() > 0){
for (Connection c : m_usedConnection) {
if(c.isClosed()){
conns.add(c);
list.add(c);
}
}
m_usedConnection.removeAll(list);
}
}
public static void main(String[] args) {
String file = "config/db_config.properties";
try {
Utils.getProperties(file);
DBConnectPool.createConnectionPool();
System.out.println("创建连接池之后conns的大小:" + conns.size());
Connection conn = getConnection();
System.out.println("获取链接之后conns大小:" + conns.size());
Statement st = conn.createStatement();
String sql = "select * from t_user";
ResultSet rs = st.executeQuery(sql);
while(rs.next()){
System.out.print(rs.getInt("id"));
System.out.print(rs.getString("name"));
System.out.println(rs.getString("ip"));
System.out.println("---------------------------");
}
System.out.println("使用的链接:" + m_usedConnection.size());
conn.close();
closedConnectionPool();
System.out.println("释放资源后使用的链接:" + m_usedConnection.size());
System.out.println("连接池的数量:" + conns.size());
} catch (Exception e) {
e.printStackTrace();
}
}
} |
|