在连接数量及连接时间(是否超时)上面没有很好的处理,望多指教!
package com.dlut.zxf.sql;
import java.util.*;
import java.sql.*;
public class ConnectionPool {
private Hashtable connections = new Hashtable();
private Properties props;
public ConnectionPool(Properties pros, int initialConnections)
throws SQLException, ClassNotFoundException {
this.props = props;
initializePool(props, initialConnections);
}
public ConnectionPool(String driverClassName, String dbURL,
String user, String password, int initialConnections)
throws SQLException, ClassNotFoundException {
props = new Properties();
props.put("connection.driver", driverClassName);
props.put("connection.url", dbURL);
props.put("user", user);
props.put("password", password);
initializePool(props, initialConnections);
}
/*
* 得到一个新的连接
*/
public Connection getConnection() throws SQLException {
Connection conn = null;
Enumeration connEnum = connections.keys();
synchronized(connections) {
while(connEnum.hasMoreElements()) {
conn = connEnum.nextElement();
Boolean b = connections.get(conn);
if (b.equals(Boolean.FALSE)) {
try {
conn.setAutoCommit(true);
} catch(SQLException e) {
e.printStackTrace();
connections.remove(conn);
conn = getNewConnection();
}
connections.put(conn, Boolean.TRUE);
//connections.put(conn, Boolean.FALSE); ?
return conn;
}
}
conn = getNewConnection();
connections.put(conn, Boolean.TRUE);
return conn;
}
}
public void returnConnection(Connection returned) {
if (connections.containsKey(returned)) {
connections.put(returned, Boolean.FALSE);
}
}
private void initializePool(Properties props, int initialConnections)
throws SQLException, ClassNotFoundException {
Class.forName(props.getProperty("connection.driver"));
for (int i=0; i
Connection conn = getNewConnection();
connections.put(conn, Boolean.FALSE);
}
}
private Connection getNewConnection() throws SQLException {
return DriverManager.getConnection(props.getProperty("connection.url"), props);
}
} 源代码下载
|
文件: | ConnectionPool.rar |
大小: | 0KB |
下载: | 下载 |
|
阅读(1262) | 评论(0) | 转发(0) |