在处理大批量数据的时候,简单的JDBC 方式未必是有用的,这个时候,要是有个链接池
会不会让你使用起来很舒服呐,那答案是必须的吗。
不多说了,说那么多,还不如直接看结果来的实际点。。。 看下面的codes
static Logger logger = Logger.getLogger(DBConnectionPool.class.getName());
public ArrayList<Connection> freeConnections = new ArrayList<Connection>();// 容器,空闲连接
private int isUsed; // 被用过的链接.
private int maxConn; // 最大连接
private int minConn; // 最小连接
private String password; // 密码
private String url; // 数据库连接地址
private String driver; // 驱动
private String user; // 用户名
/**
* 创建连接池
*
* @param driver
* @param URL
* @param user
* @param password
* @param maxConn
* @param minConn
*/
public DBConnectionPool( String driver, String url, String user, String password, int maxConn,int minConn) {
this.driver = driver;
this.url = url;
this.user = user;
this.password = password;
this.maxConn = maxConn;
this.minConn = minConn;
//创建链接.
createConns();
}
/**
* 添加资源
*
* @param con
*/
public void createConns() {
try {
for (int i = 0; i < this.maxConn; i++) {
Connection conn = newConnection();
if (conn!=null) {
//添加资源.
this.freeConnections.add(conn);// 添加到空闲连接的末尾
}
}
} catch (Exception e) {
logger.error("创建链接池失败!"+e.getLocalizedMessage());
}
logger.info("共创建了 "+freeConnections.size()+" 条链接!");
}
/**
*
* 从连接池里得到连接
*
* @return
*/
public synchronized Connection getConnection() {
try {
Connection conn = null;
if (this.freeConnections.size() > this.minConn) {
conn = (Connection) this.freeConnections.get(0);
if (conn!=null) {
this.freeConnections.remove(conn);// 如果连接分配出去了,就从空闲连接里删除
}else {
conn = getConnection(); // 继续获得连接
}
}else if (this.freeConnections.size() == this.minConn) {
//增加链接池.
createConns();
}else {
conn = newConnection(); // 新建连接
}
if (conn != null) {
this.isUsed++;
logger.info("连接池中会创建的链接共有"+this.maxConn+"个,现在的所剩余的链接是:"+freeConnections.size() +",程序调用链接的次数是:" + isUsed);
}
return conn;
} catch (Exception e) {
logger.error("获取数据链接失败!"+e.getLocalizedMessage());
return null;
}
}
/**
* 释放全部连接
*
*/
public void releaseAll() {
Iterator allConns = this.freeConnections.iterator();
while (allConns.hasNext()) {
Connection con = (Connection) allConns.next();
try {
con.close();
con=null;
} catch (SQLException e) {
logger.error("释放链接资源失败!");
}
}
//释放资源.
this.freeConnections.clear();
}
/**
* 创建新连接
*
* @return
*/
private synchronized Connection newConnection() {
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url, user, password);
if (connection!=null) {
return connection;
}
} catch (ClassNotFoundException e) {
logger.error("找不到链接DB的driver , sorry can't find db driver!");
return null;
} catch (SQLException e1) {
logger.error("sorry can't create Connection!");
return null;
}
return null;
}
不过,这个玩意,得是要配合 http://blog.csdn.net/supingemail/article/details/40431231 的这个玩意使用吧,要是没有这个玩意
那你使用个毛蛋呀。
我操那个乖乖了,这破玩意,说实话,和人家水牛比起来,写的逊色多了,哎,苦逼的 攻城狮, 程序猿,
天天和这个玩意打交道,实在是可悲的很啦。