DBCP
DBCP(DataBase connection pool)数据库连接池是 apache 上的一个Java连接池项目。DBCP通过连接池预先同数据库建立一些连接放在内存中(即连接池中),应用程序需要建立数据库连接时直接到从接池中申请一个连接使用,用完后由连接池回收该连接,从而达到连接复用,减少资源消耗的目的。
DBCP所依赖的jar包(以下例子基于如下jar包版本)
commons-dbcp2-2.1.1.jar commons-logging-1.2.jar commons-pool2-2.4.2.jar
DBCP配置文件dbcp.properties
#连接设置
driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/数据库名?useUnicode=true&characterEncoding=utf-8&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username=root//数据库账号
password=数据库密码
#<!-- 初始化连接 -->
initialSize=10
#最大连接数量
maxActive=50
#<!-- 最大空闲连接 -->
maxIdle=20
#<!-- 最小空闲连接 -->
minIdle=5
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000
#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;]
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=gbk
#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true
#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=READ_UNCOMMITTED
DBCP连接工具类
package tools
;
import org
.apache
.commons
.dbcp2
.BasicDataSource
;
import org
.apache
.commons
.dbcp2
.BasicDataSourceFactory
;
import org
.apache
.log4j
.Logger
;
import java
.io
.InputStream
;
import java
.lang
.reflect
.Field
;
import java
.lang
.reflect
.Method
;
import java
.sql
.*
;
import java
.util
.*
;
public class DbcpPool {
private static final Logger log
= Logger
.getLogger(DbcpPool
.class);
private static Connection conn
=null
;
private static PreparedStatement stmt
=null
;
private static ResultSet rs
;
private static BasicDataSource bs
;
static {
loadConfig();
}
private static void loadConfig() {
InputStream is
= DbcpPool
.class.getResourceAsStream("dbcp.properties");
Properties pr
= new Properties();
try{
pr
.load(is
);
bs
= BasicDataSourceFactory
.createDataSource(pr
);
}catch (Exception e
){
System
.out
.println(e
);
}
}
private Connection
getConnection(){
try{
conn
= bs
.getConnection();
}catch (SQLException e
){
System
.out
.println(e
);
}
return conn
;
}
private void close(){
try{
rs
.close();
stmt
.close();
conn
.close();
}catch (SQLException e
){
log
.error("资源关闭异常:",e
);
}
}
public List
<Map
<String,Object>> find(String sql
) throws SQLException
{
Connection con
=getConnection();
stmt
= con
.prepareStatement(sql
);
rs
=stmt
.executeQuery();
ResultSetMetaData md
= rs
.getMetaData();
int count
=md
.getColumnCount();
List
<Map
<String, Object>> l
= new ArrayList<>();
while (rs
.next()){
HashMap
<String, Object> mp
= new HashMap<>();
for(int i
=0;i
<count
;i
++){
String key
=md
.getColumnName(i
+1);
Object value
=rs
.getObject(key
);
if(value
==null
) value
="";
mp
.put(key
,value
);
}
l
.add(mp
);
}
close();
return l
;
}
public boolean dataChange(String sql
) throws SQLException
{
Connection con
=getConnection();
stmt
= con
.prepareStatement(sql
);
boolean flag
= false;
int result
= -1;
result
= stmt
.executeUpdate();
flag
= result
> 0 ? true : false;
stmt
.close();
con
.close();
conn
.close();
return flag
;
}
public <T>T
getObject(Map
<String,Object> map
,Class
<T> targetClass
){
Iterator
<Map
.Entry
<String, Object>> iterator
= map
.entrySet().iterator();
T target
= null
;
try {
target
= targetClass
.newInstance();
while (iterator
.hasNext()) {
Map
.Entry
<String, Object> entry
= iterator
.next();
String setMethodName
= "set" + (entry
.getKey().substring(0,1).toUpperCase() + entry
.getKey().substring(1));
Field declaredField
= targetClass
.getDeclaredField(entry
.getKey());
Object value
= entry
.getValue();
Method set_method
= targetClass
.getMethod(setMethodName
, declaredField
.getType());
set_method
.invoke(target
,value
);
}
} catch (Exception e
) {
log
.error("对象封装失败:",e
);
} finally {
return target
;
}
}
}