/*
* Copyright (C)
* <a href="mailto: "></a>
* WWW
*/
package
import java
import java
/**
* <font size=
* <font color=gray>這個類為系統提供一個數據庫的連接池</font>
* <br><br>
* @see Sys_config
* @author <a href="mailto: ">Jackliu</a>
*/
public class DBPoolsManager{
static private DBPoolsManager instance; // 唯一實例
DBPools pools;
Driver theDrv;
/**
* 構造方法
* <br>創建數據庫連接池(oracle OCI)
*/
private DBPoolsManager(){
/* use oracle OCI
String url = "jdbc:oracle:oci
String user = Sys_config
String password = Sys_config
int max = Integer
try{
/*use mysql driver
theDrv = new org
/*use oracle driver*/
theDrv = new oracle
DriverManager
}
catch ( SQLException e ){
//debug to err
e
}
pools = new DBPools(url
pools
}
/**
* 得到一個數據庫的連接池管理的實例
* @return 返回一個數據庫連接池管理的一個實例
*/
static synchronized public DBPoolsManager getInstance(){
if (instance == null){
instance = new DBPoolsManager();
}
return instance;
}
/**
* 從數據庫連接池中獲取一個空閒的數據庫連接實例
* <br>如果超出連接池的最大連接
* @return 返回一個數據庫連接對象
*/
public Connection getConnection(){
return pools
}
/**
* 釋放一個正在工作的數據庫連接到數據庫連接池
* @param con Connection 一個數據庫連接
*/
public void freeConnection(Connection con){
pools
}
/**
* 關閉數據庫連接池
*/
public void close(){
try{
pools
pools
DriverManager
}
catch ( SQLException e ){
//debug to err
e
}
}
class DBPools{
private Vector freeConnections = new Vector();
private Vector currentConnections = new Vector();
private int maxConn;
private String URL;
private String password;
private String user;
/**
* 構造函數
* <br>創建一個數據庫連接池
* @param URL String JDBC URL
* @param user String User id || null
* @param password String User pwd ||null
* @param maxConn int Max connect
*/
public DBPools(String URL
this
this
this
this
}
/**
* 釋放一個正在工作的數據庫連接到數據庫連接池
* @param con Connection 一個數據庫連接
*/
public synchronized void freeConnection(Connection con){
//remove from freeConnection vector
currentConnections
freeConnections
}
/**
* 從連接池獲得一個可用連接
* 數限制
* 然後遞歸調用自己以嘗試新的可用連接
* @return 返回一個數據庫連接對象
*/
public synchronized Connection getConnection(){
Connection con = null;
if (freeConnections
// 獲取向量中第一個可用連接
con = (Connection) freeConnections
freeConnections
try{
if (con
//遞歸調用自己
con = getConnection();
}
currentConnections
}
catch (SQLException e){
//遞歸調用自己
con = getConnection();
}
}
else if (maxConn ==
con = newConnection();
}
return con;
}
/**
* 關閉數據庫連接池
*/
public void close(){
for ( int i=
try{
((Connection)freeConnections
}
catch( SQLException e ){
//debug to err
e
}
}
for ( int i=
try{
((Connection)currentConnections
}
catch( SQLException e ){
//debug to err
e
}
}
}
/**
* 創建新的連接
*/
private synchronized Connection newConnection(){
OADS_log
//showDetail();
Connection con = null;
try{
if (user == null){
con = DriverManager
}
else{
con = DriverManager
}
currentConnections
catch (SQLException e){
return null;
}
return con;
}
/**
* 顯示數據庫連接池的狀態信息
*/
public void showDetail(){
OADS_log
OADS_log
}
}
}
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19689.html