?? poolbean.java
字號(hào):
//package eshop;
import java.sql.*;
import java.util.*;
public class PoolBean {
private int inUse=0; //實(shí)際使用中的連接數(shù)
private int maxconn; //連接池支持的最大連接數(shù)
private Vector connections=new Vector();
private String poolMessage; //連接池的狀態(tài)
private String driver; //數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序
private String url; //數(shù)據(jù)庫(kù)URL
private String username; //數(shù)據(jù)庫(kù)用戶(hù)名
private String password; //數(shù)據(jù)庫(kù)密碼
/*構(gòu)造函數(shù)*/
public PoolBean() {
//this.driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
//this.url="jdbc:microsoft:sqlserver://127.0.0.1:1433;DatabaseName=eshop";
this.driver="sun.jdbc.odbc.JdbcOdbcDriver";
this.url="jdbc:odbc:MyDataSource";
this.username="sa";
this.password="";
this.maxconn=100;
this.poolMessage="構(gòu)造成功!";
}
/*將連接返回給連接池*/
public synchronized void releaseConnection(Connection conn){
connections.addElement(conn);
inUse--;
}
/*從連接池得到一個(gè)連接*/
public synchronized Connection getConnection(){
Connection conn=null;
if(connections.size()>0){
conn=(Connection)connections.elementAt(0);
connections.removeElementAt(0);
try{
if(conn.isClosed()){
conn=getConnection();
}
}
catch(Exception e){
e.printStackTrace();
poolMessage="錯(cuò)誤!試圖獲取連接時(shí)出錯(cuò)!";
}
}
else if(maxconn==0||inUse<maxconn){
conn=newConnection();
}
if(conn!=null){
inUse++;
}
return conn;
}
/*創(chuàng)建新的連接*/
private Connection newConnection(){
Connection conn=null;
try{
Class.forName(driver);
conn=DriverManager.getConnection(url,username,password);
}
catch(Exception e){
e.printStackTrace();
poolMessage="錯(cuò)誤!建立連接時(shí)出錯(cuò)!";
return null;
}
return conn;
}
/*關(guān)閉所有的連接*/
public synchronized void closeConn(){
Enumeration allConnections=connections.elements();
while(allConnections.hasMoreElements()){
Connection conn=(Connection)allConnections.nextElement();
try{
conn.close();
}
catch(Exception e){
e.printStackTrace();
poolMessage="錯(cuò)誤!關(guān)閉連接時(shí)錯(cuò)誤!";
}
connections.removeAllElements();
}
}
/*返回連接池的消息*/
public String getPoolMessage(){
return poolMessage;
}
}
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -