数据库连接池
下面是ConnectionObject类主要方法的程序代码:
package guo.test.ConnectionPool;
public class ConnectionObject {
private Connection conn; // 数据库连接属性;
private boolean isUse; // 连接使用状态属性,连接对象当前是否在使用;
private int useCount; // 连接使用次数属性,记录连接对象的使用次数
public ConnectionObject(String url, String username, String password) {
try {
if (username.equals( " ") || password.equals( " ")) {
conn = DriverManager.getConnection(url);
} else {
conn = DriverManager.getConnection(url, username, password);
}
} catch (
SQLException e) {
System.err.print(e.getMessage());
}
catch(
NullPointerException e){
System.err.print(e.getMessage());
}
isUse = false;// 初始化连接对象的使用状态为空闭
useCount = 0;// 初始化连接对象的使用次数为0
}
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public boolean getIsUse() {
return isUse;
}
public void setIsUse(boolean isUse) {
this.isUse = isUse;
}
public int getUseCount() {
return useCount;
}
public void setUseCount(int useCount) {
this.useCount = useCount;
}
public int addUseCount() {
return useCount++;
}
}
package guo.test.ConnectionPool;
public class ConnectionPool {
private String driver = " "; // 数据库驱动程序;
private String url = " "; // 数据库存放的url;
private String username = " "; // 数据库用户名;
private String password = " "; // 数据库用户密码;
private static Vector pool = new Vector(); // 用Vector对象作为连接池;
private int connectionPoolSize; // 初始化时,连接池中建立的连接对象数目
private int connectionPoolMaxsize; // 连接池的上限,至多能建立的连接连接对象数目;
private int connectionmaxUseCount; // 一个连接对象最多能被使用的次数;
private int timeout; // 用来记录连接超时的时间;
private void loadprop() {
InputStream is = getClass().getResourceAsStream( "dbconfig.txt ");
Properties props = new Properties();
try {
props.load(is);
} catch (
IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
driver = props.getProperty( "db.driver ");
url = props.getProperty( "db.url ");
username = props.getProperty( "db.username ");
password = props.getProperty( "db.password ");
connectionPoolSize = Integer.parseInt(props
.getProperty( "db.minconnect "));
connectionPoolMaxsize = Integer.parseInt(props
.getProperty( "db.maxconnection "));