JDBC.conf配置文件:
driverClassname=com.mysql.jdbc.Driver
db_url=jdbc:mysql://localhost:3306/everdb
username=root
pwd=root
poolsize=10
连接池实现:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Vector;
public class ConnectionPool {
private Vector<Connection> pool;
private String url;
private String username;
private String password;
private String driverClassName;
private int poolSize = 2;
private static ConnectionPool instance = null;
private ConnectionPool()
{
init();
}
private void init() {
pool = new Vector<Connection>(poolSize);
readConfig();
addConnection();
}
private void addConnection() {
Connection conn = null;
for (int i = 0; i <= poolSize; i++)
{
try {
Class.forName(driverClassName);
conn = DriverManager.getConnection(url, username, password);
pool.add(conn);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void readConfig() {
try {
Properties ps = new Properties();
String Path = System.getProperty("user.dir") + "\\WebContent\\conf\\JDBC.conf";
FileInputStream fs = new FileInputStream(Path);
ps.load(fs);
fs.close();
this.url = ps.getProperty("db_url");
this.username = ps.getProperty("username");
this.password = ps.getProperty("pwd");
this.driverClassName = ps.getProperty("driverClassname");
this.poolSize = Integer.parseInt(ps.getProperty("poolsize"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.err.println("Get Config Data Error!");
}
}
//获得实例,给外部类进行获取连接池
public static ConnectionPool getInstance()
{
if (instance == null){
instance = new ConnectionPool();
}
return instance;
}
public synchronized Connection getConnection()
{
if (pool.size() > 0 )
{
Connection conn = pool.get(0);
pool.remove(conn);
return conn;
}else{
return null;
}
}
public synchronized void release(Connection conn)
{
pool.add(conn);
}
public synchronized void closePool(){
for (int i=0; i<pool.size();i++){
try {
((Connection)pool.get(i)).close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pool.remove(i);
}
}
}