日期:2014-05-16  浏览次数:20431 次

数据库连接池的简单实现

这是我以前写的一段程序,试图按着自己对多线程与JDBC的理解,实现数据库链接池的功能。运行时也还正常,就是感觉程序太简单。现在看起来也的确太简单,好多复杂的情形都没有考虑到。

?

包结构:
org.eleaf.java.eshop.db/
|---db.properties
|---Database.java
|---ConnectionPool.java

db.properties:配置文件

##--------------
# MySql
#--------------
#db.driver=com.mysql.jdbc.Driver
#db.username=bitan
#db.password=abcd
#db.url=jdbc:mysql://localhost/eshop?useUnicode=true&characterEncoding=GBK
#db.maxConnections=10
#--------------
# Sql Server
#--------------
db.driver=com.jnetdirect.jsql.JSQLDriver
db.username=sa
db.password=
db.url=jdbc:JSQLConnect://server/database=xxxx
db.maxConnections=10
#--------------
# Oracle
#--------------
#db.driver=oracle.jdbc.driver.OracleDriver
#db.username=xxx
#db.password=xxx
#db.url=jdbc:oracle:thin:@SERVER:1521:ORACLEDB
#db.maxConnections=10

?

?

Database.java:从配置文件读取信息,创建数据库连接

/*
* Created on 2005-2-19
*
*/
package org.eleaf.java.eshop.db;

import java.sql.*;
import java.io.*;
import org.eleaf.java.eshop.mvc.util.*;


public class Database {
private static Database instance;
private final String propFile="db.properties";
private final String driver;
private final String url;
private final String username;
private final String password;
private final int maxConnections;
public static Database getInstance() throws SQLException{
if (instance == null) {
instance = new Database();
}
return instance;
}
private Database() throws SQLException{
try {
PropertiesParser parser = new PropertiesParser(propFile, this);
driver = parser.getValue("db.driver");
url = parser.getValue("db.url");
username = parser.getValue("db.username");
password = parser.getValue("db.password");
String strMaxConns = parser.getValue("db.maxConnections");
maxConnections = Integer.parseInt(strMaxConns);
} catch (IOException e) {
throw new SQLException("IOException: " + e.getMessage());
}
}

/**
* @return Returns the driver.
*/
public String getDriver() {
return driver;
}
/**
* @return Returns the password.
*/
public String getPassword() {
return password;
}
/**
* @return Returns the url.
*/
public String getUrl() {
return url;
}
/**
* @return Returns the username.
*/
public String getUsername() {
return username;
}

/**
* @return Returns the maxConnections.
*/
public int getMaxConnections() {
return maxConnections;
}
/**
* @return Returns the propFile.
*/
public String getPropFile() {
return propFile;
}
Connection getConnection() throws SQLException{
Connection conn = null;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url, username, password);
} catch (Exception e) {
throw new SQLException(e.getMessage());
}
return conn;
}
}



ConnectionPool.java:数据库连接池

/*
* Created on 2005-3-24
*
*/
package org.eleaf.java.eshop.db;