废话不多说直接上代码
数据库连接封装类
publicclass ConnectionProvider {
//数据
publicstaticfinal String DRIVER = "sun.jdbc.odbc.JdbcOdbcDriver";
publicstaticfinal String URL = "jdbc:odbc:storedb";
publicstaticfinal String USER = "";
publicstaticfinal String PASSWD = "";
//加载驱动
//用静态块可以确保只加载一次
static {
try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//获取连接
public Connection getConnection() throws SQLException{
return DriverManager.getConnection(URL,USER,PASSWD);
}
}
连接池类
package fei.db;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
/**
* @author fei
* 连接池设计
*
*/
publicclass ConnectionPool {
//连接集合
private ArrayList<Connection> pool = new ArrayList<Connection>();
//连接最大个数
privateintmax;
//连接提供者
private ConnectionProvider provider = new ConnectionProvider();
public ConnectionPool(int max){
this.max = max ;
}
//取出空闲连接
public Connection getConnection() throws SQLException{
Connection conn = null;
synchronized (pool) {//加锁因为是多用户操作
if(!pool.isEmpty()){
conn = pool.remove(0);//取连接,第一个肯定有
return conn;
}
}
//如果池中为空
conn = provider.getConnection();
return conn;
}
//放回连接池
publicvoid release(Connection conn) throws SQLException{
synchronized (pool) {
if(pool.size() < max){
pool.add(conn);
}
else{
conn.close();
}
}
}
//关闭连接池
publicvoid closeConn() throws SQLException{
synchronized (pool) {
for (Connection conn : pool) {
if(!pool.isEmpty()){
pool.remove(conn);
conn.close();
}
}
}
}
}
测试(代码段)
//使用连接池
ConnectionPool pool = new ConnectionPool(10);
for (int i = 0; i < 500; i++) {
Connection conn = pool.getConnection();
Statement stm = conn.createStatement();
stm.executeUpdate(sql);
pool.release(conn);
}
pool.closeConn();