?? dbconnpool.java~7~
字號:
package stumng;
import java.sql.*;
import java.util.*;
/*連接池類.能夠根據要求創建新連接,直到最大連接數為止.*/
public class DBConnPool {
//實際使用中的連接數
private int inUse=0;
//空閑連接
private Vector connections = new Vector();
//連接池名
private String poolname;
//數據庫標識
private String dbid;
//驅動程序名
private String drivername;
//數據庫賬號
private String username;
//數據庫密碼
private String passwd;
//最大連接數
private int maxconn;
public DBConnPool(String poolname, String drivername, String dbid, String username, String passwd, int maxconn) {
this.poolname = poolname;
this.dbid = dbid;
this.drivername = drivername;
this.username = username;
this.passwd = passwd;
this.maxconn = maxconn;
}
/*將連接返回給連接池*/
public synchronized void releaseConnection(Connection con) {
// 將指定連接加入到向量末尾
connections.addElement(con);
//連接數減一
inUse--;
}
/*從連接池得到一個連接*/
public synchronized Connection getConnection() {
Connection con = null;
if (connections.size() > 0) {
// 獲取連接列表中獲得第一個連接
con = (Connection) connections.elementAt(0);
connections.removeElementAt(0);
//如果此連接已關閉,則繼續獲取
try {
if (con.isClosed())
con = getConnection();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
//如果實際使用的連接小于最大連接數,就新創建一個連接
else if (maxconn == 0 || inUse < maxconn) {
con = newConnection();
}
if (con != null) {
//連接數增一
inUse++;
}
//返回一個連接
return con;
}
/*創建新的連接*/
private Connection newConnection() {
Connection con = null;
try {
//加載驅動程序
Class.forName(drivername);
//建立連接
con = DriverManager.getConnection(dbid, username, passwd);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
//返回該連接
return con;
}
/*關閉所有連接*/
public synchronized void closeConn() {
Enumeration allConnections = connections.elements();
while (allConnections.hasMoreElements()) {
Connection con = (Connection) allConnections.nextElement();
try {
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
connections.removeAllElements();
}
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -