package
test;
import
java.sql.*;
import java.util.*;
public class DBConnpool
{
private int inUse = 0;
private Vector<Connection> connections = new Vector<Connection>();
private String poolname = "dbconnpool";
private String dbid = "jdbc:mysql://localhost:3306/teasystem";
private String drivername = "com.mysql.jdbc.Driver";
private String username = "root";
private String password = "123";
private int maxconn = 5000;
public DBConnpool(){}
public void setdbid(String dbid)
{
this.dbid = dbid;
}
public void setusername(String username)
{
this.username = username;
}
public void setpassword(String password)
{
this.password = password;
}
public void setmaxconn(int maxconn)
{
this.maxconn = maxconn;
}
public String getdbid()
{
return dbid;
}
public String getusername()
{
return username;
}
public String getpassword()
{
return password;
}
public int getmaxconn()
{
return maxconn;
}
//将连接返还给连接池
public synchronized void reConnection(Connection conn)
{
Connection con = conn;
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 e){
e.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,password);
}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();
}
}
}
}
使用连接池,把暂时不使用的链接放入连接池,到需要使用的时候,从连接池中取出链接使用