连接池技术的核心思想是:连接复用,通过建立一个数据库连接池以及一套连接使用、分配、管理策略,使得该连接池中的连接可以得到高效、安全的复用,避免了数据库连接频繁建立、关闭的开销。另外,由于对JDBC中的原始连接进行了封装,从而方便了数据库应用对于连接的使用(特别是对于事务处理),提高了开发效率,也正是因为这个封装层的存在,隔离了应用的本身的处理逻辑和具体数据库访问逻辑,使应用本身的复用成为可能。连接池主要由三部分组成(如下图所示):连接池的建立、连接池中连接的使用管理、连接池的关闭。
/**
*@Description: 数据库连接池配置
*/
package com.lulei.db.manager;
import org.apache.log4j.Logger;
import com.lulei.util.ClassUtil;
public class DBPool {
private static DBPool dbPool = null;
private String poolPath;
private static Logger log = Logger.getLogger(DBPool.class);
private static String path = ClassUtil.getClassRootPath(DBPool.class);
public static DBPool getDBPool(){
if (dbPool == null){
synchronized(DBPool.class){
if (dbPool == null){
dbPool = new DBPool();
}
}
}
return dbPool;
}
private DBPool(){
}
/**
* @param poolPath
* @Author: lulei
* @Description: 设置数据库连接池配置文件路径
*/
public void setPoolPath(String poolPath){
this.poolPath = poolPath;
}
/**
* @return
* @Author: lulei
* @Description: 返回数据库连接池配置文件路径
*/
protected String getPoolPath(){
//如果没有指定配置文件,则使用默认配置文件
if (poolPath == null){
poolPath = path + "proxool.xml";
log.info("Database's poolpath is null, use default path:" + poolPath);
}
return poolPath;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<proxool-config>
<proxool>
<alias>novelSelect</alias>
<driver-url><![CDATA[jdbc:mysql://172.20.37.73:3306/novel?characterEncoding=utf-8]]></driver-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver-properties>
<property name="user" value="root"/>
<property name="password" value="root"/>
</driver-properties>
<house-keeping-sleep-time>900000</house-keeping-sleep-time>
<maximum-active-time>500000</maximum-active-time>
<maximum-connection-count>40</maximum-connection-count>
<minimum-connection-count>4</minimum-connection-count>
<house-keeping-test-sql>select 1</house-keeping-test-sql>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
</proxool>
<proxool>
<alias>novelEdit</alias>
<driver-url><![CDATA[jdbc:mysql://172.20.37.73:3306/novel?characterEncoding=utf-8]]></driver-url>
<driver-class>com.mysql.jdbc.Driver</driver-class>
<driver-properties>
<property name="user" value="root"/>
<property name="password" value="root"/>
</driver-properties>
<house-keeping-sleep-time>900000</house-keeping-sleep-time>
<maximum-active-time>500000</maximum-active-time>
<maximum-connection-count>10</maximum-connection-count>
<minimum-connection-count>4</minimum-connection-count>
<house-keeping-test-sql>select 1</house-keeping-test-sql>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
</proxool>
</proxool-config>
JAXPConfigurator.configure(DBPool.getDBPool().getPoolPath(), false);
Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");return DriverManager.getConnection(poolName);
/**
*@Description: 数据库连接池管理
*/
package com.lulei.db.manager;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import org.logicalcobwebs.proxool.configuration.JAXPConfigurator;
public class DBManager {
private static DBManager dBManager = null;
private DBManager(){
try {
JAXPConfigurator.configure(DBPool.getDBPool().getPoolPath(), false);
Class.forName("org.logicalcobwebs.proxool.ProxoolDriver");
} catch (Exception e){
e.printStackTrace();
}
}
/**
* @return DBManager
* @Author: lulei
* @Description: 获取数据库连接池管理对象
*/
protected static DBManager getDBManager(){
if (dBManager == null){
synchronized(DBManager.class){
if (dBManager == null){
dBManager = new DBManager();
}
}
}
return dBManager;
}
/**
* @param poolName
* @return Connection
* @throws SQLException
* @Author: lulei
* @Description: 获取数据库链接
*/
protected Connection getConnection(String poolName) throws SQLException{
return DriverManager.getConnection(poolName);
}
}
/**
*@Description: 数据库操作
*/
package com.lulei.db.manager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import org.apache.log4j.Logger;
public class DBOperation {
private static Logger log = Logger.getLogger(DBOperation.class);
private Connection conn = null;
private String poolName;
/**
* @param poolName
*/
public DBOperation(String poolName){
this.poolName = poolName;
}
/**
* @throws SQLException
* @Author: lulei
* @Description: 获取Connection
*/
private void open() throws SQLException{
this.conn = DBManager.getDBManager().getConnection(poolName);
}
/**
* @Author: lulei
* @Description: 关闭Connection
*/
public void close() {
try {
if (this.conn != null) {
this.conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param sql组装的sql字符串
* @param params传入的参数
* @throws SQLException
* @throws ClassNotFoundException
* @Author: lulei
* @Description: 组装PreparedStatement
*/
private PreparedStatement setPres(String sql, HashMap<Integer, Object> params) throws SQLException, ClassNotFoundException{
if (null != params) {
if (0 < params.size()){
PreparedStatement pres = this.conn.prepareStatement(sql);
for (int i = 1; i <= params.size(); i++){
if (params.get(i).getClass() == Class.forName("java.lang.String")){
pres.setString(i, params.get(i).toString());
} else if (params.get(i).getClass() == Class.forName("java.lang.Integer")){
pres.setInt(i, (Integer) params.get(i));
} else if (params.get(i).getClass() == Class.forName("java.lang.Boolean")){
pres.setBoolean(i, (Boolean) params.get(i));
} else if (params.get(i).getClass() == Class.forName("java.lang.Float")){
pres.setFloat(i, (Float) params.get(i));
} else if (params.get(i).getClass() == Class.forName("java.lang.Double")){
pres.setDouble(i, (Double) params.get(i));
} else if (params.get(i).getClass() == Class.forName("java.lang.Long")){
pres.setLong(i, (Long) params.get(i));
} else if (params.get(i).getClass() == Class.forName("java.sql.Date")){
pres.setDate(i, java.sql.Date.valueOf(params.get(i).toString()));
} else {
log.info("not found class : " + params.get(i).getClass().toString());
return null;
}
}
return pres;
}
}
return null;
}
/**
* @param sql
* @return int
* @throws SQLException
* @Author: lulei
* @Description: executeUpdate
*/
protected int executeUpdate(String sql) throws SQLException{
this.open();
Statement state = this.conn.createStatement();
int re = state.executeUpdate(sql);
return re;
}
/**
* executeUpdate
* @param sql
* @param params
* @return int
* @throws SQLException
* @throws ClassNotFoundException
* @Author: lulei
* @Description:
*/
protected int executeUpdate(String sql, HashMap<Integer, Object> params) throws SQLException, ClassNotFoundException{
this.open();
PreparedStatement pres = setPres(sql, params);
int re = 0;
if (null != pres) {
re = pres.executeUpdate();
}
return re;
}
/**
* getGeneratedKeys
* @param sql
* @return ResultSet
* @throws SQLException
* @Author: lulei
* @Description:
*/
protected ResultSet getGeneratedKeys(String sql) throws SQLException{
this.open();
Statement state = this.conn.createStatement();
state.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet re = state.getGeneratedKeys();
return re;
}
/**
* getGeneratedKeys
* @param sql
* @param params
* @return ResultSet
* @throws SQLException
* @throws ClassNotFoundException
* @Author: lulei
* @Description:
*/
protected ResultSet getGeneratedKeys(String sql, HashMap<Integer, Object> params) throws SQLException, ClassNotFoundException{
this.open();
PreparedStatement pres = setPres(sql, params);
if (null != pres) {
pres.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet re = pres.getGeneratedKeys();
return re;
}
return null;
}
/**
* @param sql
* @return ResultSet
* @throws SQLException
* @Author: lulei
* @Description: executeQuery
*/
protected ResultSet executeQuery(String sql) throws SQLException{
this.open();
Statement state = this.conn.createStatement();
ResultSet re = state.executeQuery(sql);
return re;
}
/**
* @param sql
* @param params
* @return ResultSet
* @throws SQLException
* @throws ClassNotFoundException
* @Author: lulei
* @Description: executeQuery
*/
protected ResultSet executeQuery(String sql, HashMap<Integer, Object> params) throws SQLException, ClassNotFoundException{
this.open();
PreparedStatement pres = setPres(sql, params);
if (null != pres) {
ResultSet re = pres.executeQuery();
return re;
}
return null;
}
}
/**
*@Description: 增删改查四个数据库操作接口
*/
package com.lulei.db.manager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
public class DBServer {
private DBOperation dBOperation;
/**
* @param poolName
* @Description: 在使用该类之前,请保证函数DBPool.getDBPool().setPoolPath()已经运行
*/
public DBServer(String poolName){
dBOperation = new DBOperation(poolName);
}
/**
* @Author: lulei
* @Description: 释放链接,在执行完数据库操作,必须执行此命令
*/
public void close(){
dBOperation.close();
}
/**
* @param table
* @param columns
* @param params
* @return int
* @throws SQLException
* @throws ClassNotFoundException
* @Author: lulei
* @Description: insert 执行完此命令后,执行close()操作
*/
public int insert(String table, String columns, HashMap<Integer, Object> params) throws SQLException, ClassNotFoundException{
String sql = insertSql(columns, table);
return dBOperation.executeUpdate(sql, params);
}
/**
* @param sql
* @return int
* @throws SQLException
* @Author: lulei
* @Description: insert 执行完此命令后,执行close()操作
*/
public int insert(String sql) throws SQLException {
return dBOperation.executeUpdate(sql);
}
/**
* @param table
* @param columns
* @param params
* @return ResultSet
* @throws SQLException
* @throws ClassNotFoundException
* @Author: lulei
* @Description: insertGetGeneratedKeys 执行完此命令后,执行close()操作
*/
public ResultSet insertGetGeneratedKeys(String table, String columns, HashMap<Integer, Object> params) throws SQLException, ClassNotFoundException{
String sql = insertSql(columns, table);
return dBOperation.getGeneratedKeys(sql, params);
}
/**
* @param sql
* @return ResultSet
* @throws SQLException
* @Author: lulei
* @Description: insertGetGeneratedKeys 执行完此命令后,执行close()操作
*/
public ResultSet insertGetGeneratedKeys(String sql) throws SQLException{
return dBOperation.getGeneratedKeys(sql);
}
/**
* @param table
* @param condition
* @return int
* @throws SQLException
* @Author: lulei
* @Description: delete 执行完此命令后,执行close()操作
*/
public int delete(String table, String condition) throws SQLException{
if(null == table){
return 0;
}
String sql = "delete from " + table + " " + condition;
return dBOperation.executeUpdate(sql);
}
/**
* @param sql
* @return int
* @throws SQLException
* @Author: lulei
* @Description: delete 执行完此命令后,执行close()操作
*/
public int delete(String sql) throws SQLException{
return dBOperation.executeUpdate(sql);
}
/**
* @param columns
* @param table
* @param condition
* @return ResultSet
* @throws SQLException
* @Author: lulei
* @Description: select 执行完此命令后,执行close()操作
*/
public ResultSet select(String columns, String table, String condition) throws SQLException {
String sql = "select " + columns + " from " + table + " " + condition;
return dBOperation.executeQuery(sql);
}
/**
* @param sql
* @return ResultSet
* @throws SQLException
* @Author: lulei
* @Description: select 执行完此命令后,执行close()操作
*/
public ResultSet select(String sql) throws SQLException{
return dBOperation.executeQuery(sql);
}
/**
* @param table
* @param columns
* @param condition
* @param params
* @return int
* @throws SQLException
* @throws ClassNotFoundException
* @Author: lulei
* @Description: update 执行完此命令后,执行close()操作
*/
public int update(String table, String columns, String condition, HashMap<Integer, Object> params) throws SQLException, ClassNotFoundException{
String sql = updateString(table, columns, condition);
return dBOperation.executeUpdate(sql, params);
}
/**
* @param sql
* @return int
* @throws SQLException
* @Author: lulei
* @Description: update 执行完此命令后,执行close()操作
*/
public int update(String sql) throws SQLException{
return dBOperation.executeUpdate(sql);
}
/**
* @param table
* @param columns
* @param condition
* @return String
* @Author: lulei
* @Description: 组装updateString
*/
private String updateString(String table, String columns, String condition) {
if (null == columns || null == table) {
return "";
}
String[] column = columns.split(",");
StringBuilder stringBuilder = new StringBuilder("update ");
stringBuilder.append(table);
stringBuilder.append(" set ");
stringBuilder.append(column[0]);
stringBuilder.append("=?");
for (int i = 1; i < column.length; i++){
stringBuilder.append(", ");
stringBuilder.append(column[i]);
stringBuilder.append("=?");
}
stringBuilder.append(" ");
stringBuilder.append(condition);
return stringBuilder.toString();
}
/**
* @param columns
* @param table
* @return String
* @Author: lulei
* @Description: 组装insertSql
*/
private String insertSql(String columns, String table){
if (null == columns || null == table) {
return "";
}
int colNum = columns.split(",").length;
StringBuilder stringBuilder = new StringBuilder("insert into ");
stringBuilder.append(table);
stringBuilder.append(" (");
stringBuilder.append(columns);
stringBuilder.append(") values (?");
for (int i = 1; i < colNum; i++) {
stringBuilder.append(",?");
}
stringBuilder.append(")");
return stringBuilder.toString();
}
}
public boolean support(String docNo){
DBServer dbServer = new DBServer(dbPoolName);
String editTime = System.currentTimeMillis() + "";
String sql = "update " + SolutionTable.tableName + " set " + SolutionTable.support + "=" + SolutionTable.support + "+1, " + SolutionTable.editTime + "='"+ editTime+"' where " +SolutionTable.docNo + "='" + docNo + "'";
try {
return dbServer.update(sql) > 0;
} catch (SQLException e) {
e.printStackTrace();
} finally {
dbServer.close();
}
return false;
}原文地址:http://blog.csdn.net/xiaojimanman/article/details/43272993