高分请教!!老大们请给小弟看看!先谢了!
cnlsq 2002-06-28 03:12:19 我有一段代码是连接池用的,能编译出来,可就是不连不上不知怎的:我的代码:
package sql;
import java.lang.*;
import java.sql.*;
import java.util.*;
public class connPool{
private static final int defaultMaxConnections=3;
private Vector freeConnections;
private Hashtable boundConnections;
private String driverName;
private String jdbcURL;
private String username;
private String password;
private int maxConnections;
private Driver dv;
public connPool(int numConnections)
{
maxConnections=numConnections;
boundConnections=null;
freeConnections=null;
driverName="org.gjt.mm.mysql.Driver";
dv=(Driver)Class.forName(driverName).newInstance();
jdbcURL="jdbc:mysql://mysql.langkey.loc/weblin";
username="l";
password="l";
}
public connPool(){
this(defaultMaxConnections);
}
public void closeDB() throws SQLException{
if(boundConnections!=null){
for(Enumeration e=boundConnections.elements();
e.hasMoreElements();){
Connection conn=(Connection)e.nextElement();
conn.close();
}
boundConnections.clear();
boundConnections=null;
}
if (freeConnections!=null){
for(Enumeration e=freeConnections.elements();
e.hasMoreElements();){
Connection conn=(Connection)e.nextElement();
conn.close();
}
freeConnections.removeAllElements();
freeConnections=null;
}
}
public synchronized Connection getConnection()
throws SQLException{
if(freeConnections==null)
throw new SQLException(
"The connection pool has not been established yet.");
if(boundConnections.get(Thread.currentThread())!=null) throw new SQLException(
"Cannot get connections over once for this current running thread.");
try{
if(freeConnections.size()==0)
wait();
}
catch(InterruptedException ex){
throw new SQLException(ex.toString());
}
Connection conn=(Connection)freeConnections.firstElement();
freeConnections.removeElement(conn);
boundConnections.put( Thread.currentThread(),conn);
return conn;
}
public void openDB(String drvName,String url,String uname,String passwd)
throws SQLException{
try{
boundConnections=new Hashtable(maxConnections);
freeConnections=new Vector(maxConnections);
Class.forName(drvName);
for(int i=0;i<maxConnections;i++)
freeConnections.addElement(
DriverManager.getConnection(url,uname,passwd));
}
catch(Exception ex){
boundConnections=null;
freeConnections=null;
throw new SQLException(ex.toString());
}
}
public synchronized void reurnConnection()
throws SQLException{
Connection conn=
(Connection)boundConnections.remove(Thread.currentThread());
if(conn==null)
throw new SQLException(
"The connection which this current running thread got is not fond.");
notify();
}
public void setConnectionSwitch(String on_off){
try{
if(on_off.equalsIgnoreCase("on"))
openDB(driverName,jdbcURL,username,password);
else if(on_off.equalsIgnoreCase("off"))
closeDB();
}
catch (SQLException ex){
System.out.println(ex.toString());
}
}
public boolean isConnection(){
if(dv.acceptsURL(jdbcURL))
return true;
else
return false;
}
public void setMaxConnections(int numConnections){
maxConnections=numConnections;
}
}