JDBC数据库连接池的简单实现、读取资源配置文件、不是太完善、请多提建议。。。
package com.xxm.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* 池化连接
* @author D-xxm
*/
public class DbCon {
private static Properties psCon = new Properties();
static int minCon = 3; // 最小连接数
static int maxCon = 10; // 最大连接数
private static List<Connection> listCon = new ArrayList<Connection>(); // 连接池
/**
* 初始化连接池
*/
static {
try {
loadPs();
for(int i=0;i<minCon;i++){
listCon.add(getCon());
}
} catch (IOException e) {
System.out.println("资源文件找不到。。。");
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("连接驱动包。。。");
e.printStackTrace();
}catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 读取资源文件配置、加载驱动
* @throws IOException
* @throws ClassNotFoundException
*/
private static void loadPs() throws IOException, ClassNotFoundException {
if (psCon == null)
psCon = new Properties();
if (psCon.size() < 4) {
InputStream is = DbCon.class.getResourceAsStream("conn.properties");
psCon.load(is);
}
Class.forName(psCon.getProperty("driver"));
}
/**
* 获取数据库连接。。。
* @return
* @throws SQLException
* @throws IOException
* @throws ClassNotFoundException
*/
private static Connection getCon() throws SQLException, IOException, ClassNotFoundException{
System.out.println("--------------------------------------新建连接资源--------------------------------------");
if(psCon==null||psCon.size()<4)
loadPs();
return DriverManager.getConnection(psCon.getProperty("url"),psCon.getProperty("user"),psCon.getProperty("password"));
}
/**
* 在连接池里拿取连接、如果没有了、调用方法新建连接
* @return
* @throws SQLException
* @throws IOException
* @throws ClassNotFoundException
*/
public static Connection getConnection() throws SQLException, IOException, ClassNotFoundException{
if(listCon.size()>0)
return listCon.remove(listCon.size()-1);
return getCon();
}
/**
* 当连接小于最大连接数时、将连接放入连接池、否则关闭数据库连接
* @param con
* @throws SQLException
*/
public static void closeCon(Connection con) throws SQLException{
if(con!=null&&!con.isClosed()){
if(listCon.size()>=maxCon)
con.close();
listCon.add(con);
}
}
public static void main(String[] args) {
try {
System.out.println(getConnection());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
conn.properties资源文件:
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/demo
user=root
password=xxm