简单的jdbc连接池实现


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Vector;


public class DBPool {

private static String userName="czm";
private static String pwd="123456";
private static String driver="com.mysql.jdbc.Driver";
private static String url="jdbc:mysql://localhost:3306/test";
private static Vector<Connection> conns=new Vector<Connection>();
private static int size=5;


    static{
    try {
Class.forName(driver);
for(int i=0;i<size;i++){
    Connection conn=DriverManager.getConnection(url,userName,pwd);
    conns.add(conn);
    }
} catch (Exception e) {

e.printStackTrace();
}
   
    }

    //获取连接
    public synchronized static Connection getConnection(){
    Connection conn=null;
    if(conns.isEmpty()){
    try {
conn=DriverManager.getConnection(url,userName,pwd);
} catch (Exception e) {

e.printStackTrace();
}
   
    }else{
    return conn=conns.remove(0);
    }
    return conn;
    } 
    
    //放回连接池或释放连接
    public synchronized static void closeConnection(Connection conn,Statement stat,ResultSet rs){
    if(conns.size()<size){
    conns.add(conn);
    }else{
    if(rs!=null)
try {
rs.close();
if(stat!=null)stat.close();
    if(conn!=null)conn.close();
} catch (Exception e) {
e.printStackTrace();
}
   
    }
    }
}

 

你可能感兴趣的:(java,sql,mysql,jdbc)