日期:2014-05-17  浏览次数:20670 次

帮忙看下这个代码
[code=Java][/code]package Try;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Hashtable;

public class DBConnectionManage {

private Hashtable connectionpool;
private int maxconnection;
private int currentconn;

public DBConnectionManage(){
init();
}

public static DBConnectionManage getInstance(){
return new DBConnectionManage();
}

public void init(){
connectionpool=new Hashtable();
maxconnection=20;
currentconn=0;
initConnection();
}

public void initConnection(){

for(int i=1;i<=maxconnection/2;i++){
DBConnection addconn=this.getConnection();
connectionpool.put(i,addconn);
}
}

synchronized public DBConnection getConnection(){
DBConnection dbconn=null;
try{
String forName="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost/mydata";
String user="root";
String pwd="root";
dbconn=new DBConnection(url,user,pwd,forName,0);
currentconn++;
System.out.println("生成Connection!!!");
}catch(Exception e){
e.printStackTrace();
}
return dbconn;
}

public Connection getFreeConnection(){
Connection conn=null;
DBConnection model=null;
Object key=null;
boolean foundconnection=false;
for(int i=0;i<connectionpool.size();i++){
Enumeration e=connectionpool.keys();
while(e.hasMoreElements()){
key=e.nextElement();
model=(DBConnection)connectionpool.get(key);
conn=model.getConnection();
connectionpool.remove(key);
while(connectionpool.size()<maxconnection/2){
connectionpool.put(getMaxKey(connectionpool)+1, getConnection());
}
foundconnection=true;
System.out.println("从缓冲池中成功读取Connection");
break;
}
}
if(!foundconnection){
release();
initConnection();
model=getConnection();
conn=model.getConnection();
}
System.out.println(connectionpool.size());
return conn;
}

private int getMaxKey(Hashtable cp){
int maxkey=0;
int tmpkey=0;
Enumeration e=connectionpool.keys();
while(e.hasMoreElements()){
try{
tmpkey=Integer.parseInt(e.nextElement().toString());
}catch(Exception r){
tmpkey=0;
}
if(maxkey<tmpkey){
maxkey=tmpkey;
}
}
return maxkey;

}

public void closeConnection(Connection conn){
if(conn!=null){
try{
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}

public void release(){
Enumeration e=connectionpool.elements();
DBConnection model=null;
Connection modelconn=null;
while(e.hasMoreElements()){
model=(DBConnection)e.nextElement();
modelconn=model.getConnection();
closeConnection(modelconn);
}
}

public static void main(String[] args) {

DBConnectionManage dbmanage=DBConnectionManage.getInstance();
Connection conn=dbmanage.getFreeConnection();

String str="select * from StudentInfo";
ResultSet rs=null;
Statement stmt=null;
System.out.println(conn); // 这里输出为空 为什么?
try{
stmt=conn.createStatement();