package webgame.db;
import java.sql.*;
import java.util.*;
public class DataBase{
private static int maxConnectNum = 20;
private java.sql.Connection conn[]=new Connection[maxConnectNum];
private static ArrayList connectPool = new ArrayList();
private static int flag = 0;
public DataBase() {
if(flag == 0){
init();
}
}
private Connection getConnectionFromDatabase(){
Connection trueConn = null;
try {
//Class.forName("org.gjt.mm.mysql.Driver").newInstance();
Class.forName("com.mysql.jdbc.Driver").newInstance();
String url ="jdbc:mysql://localhost:3306/webgame?user=root&password=&useUnicode=true&characterEncoding=GBK";
trueConn= DriverManager.getConnection(url);
}
catch (Exception ex) {
System.out.println("数据连接出错了:" + ex.toString());
}
return trueConn;
}
//这里建立所有的连接;
private void init(){
for(int i=0;i<maxConnectNum;i++){
conn[i] = getConnectionFromDatabase();
connectPool.add(i,conn[i]);
}
flag = 1;
}
//从连接池中取得一个可用的连接
public Connection getConnection(){
Connection conn = null;
if(connectPool.size()==0){
try {
java.lang.Thread.sleep(1000);
getConnection();
}
catch (InterruptedException ex) {
System.out.println("连接全部用光,这里sleep出错了.");
}
}else{
conn = (Connection)connectPool.remove(0);
}
return conn;
}
//提供给外部程序调用,不用的连接放回连接池当中...
public boolean release(Connection conn){
return connectPool.add(conn);
}
public static void main(String[] args)
{
}
}