java常用工具类之数据库连接类(可以连接多种数据库)
依赖包下载:http://xiazai.jb51.net/201407/tools/java-db-dependency(jb51.net).rar
数据库连接类源码:
packagecom.itjh.javaUtil;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.PreparedStatement;
importjava.sql.ResultSet;
importjava.sql.ResultSetMetaData;
importjava.sql.SQLException;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
importorg.apache.commons.dbcp.ConnectionFactory;
importorg.apache.commons.dbcp.DriverManagerConnectionFactory;
importorg.apache.commons.dbcp.PoolableConnectionFactory;
importorg.apache.commons.dbcp.PoolingDriver;
importorg.apache.commons.dbutils.DbUtils;
importorg.apache.commons.dbutils.QueryRunner;
importorg.apache.commons.dbutils.handlers.MapListHandler;
importorg.apache.commons.pool.ObjectPool;
importorg.apache.commons.pool.impl.GenericObjectPool;
/**
*连接数据库的综合类。</br>
*依赖jar包:commons.dbcp-1.4,commons.dbutils-1.3,commons.pool-1.5.4包。
*
*@author宋立君
*@date2014年07月03日
*/
publicclassDBUtil{
privateStringdri=null;
privateStringurl=null;
privateStringusername=null;
privateStringpassword=null;
privateStringpoolName=null;//连接池名称
privateObjectPoolconnectionPool=null;//连接池
//对应的定时查询类
privateQueryThreadqueryThread=null;
/**
*功能:构造函数
*
*@author宋立君
*@date2014年07月03日
*@paramdri
*驱动全类名,例如:com.mysql.jdbc.Driver。
*@paramurl
*数据库url连接,例如:
*"jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8"
*@paramuserName
*数据库用户名,例如:root
*@parampassword
*数据库密码,例如:abc
*@parampoolName
*创建的数据库连接池的名称,例如mypool,注意一个web容器此名称不能重复。
*/
publicDBUtil(Stringdri,Stringurl,StringuserName,Stringpassword,
StringpoolName){
this.dri=dri;
this.url=url;
this.username=userName;
this.password=password;
this.poolName=poolName;
}
/**
*执行sql。
*
*@paramconn
*连接
*@parampstm
*PreparedStatement
*@returnint执行sql对应的影响行。
*@throwsSQLException
*@author宋立君
*@date2014年07月03日
*/
publicintexecute(Connectionconn,PreparedStatementpstm)
throwsSQLException{
try{
returnpstm.executeUpdate();
}finally{
Close(conn);
}
}
/**
*查询sql。
*
*@paramconn
*连接
*@parampstm
*PreparedStatement
*@returnList<Map<String,Object>>查询的结果集
*@throwsSQLException
*@author宋立君
*@date2014年07月03日
*/
publicList<Map<String,Object>>query(Connectionconn,
PreparedStatementpstm)throwsSQLException{
try{
returnresultSetToList(pstm.executeQuery());
}finally{
Close(conn);
}
}
/**
*功能:ResultSet转为List<Map<String,Object>>
*
*
*@paramrs
*ResultSet原始数据集
*@returnList<Map<String,Object>>
*@throwsjava.sql.SQLException
*@author宋立君
*@date2014年07月03日
*/
privateList<Map<String,Object>>resultSetToList(ResultSetrs)
throwsjava.sql.SQLException{
if(rs==null)
returnCollections.EMPTY_LIST;
ResultSetMetaDatamd=rs.getMetaData();//得到结果集(rs)的结构信息,比如字段数、字段名等
intcolumnCount=md.getColumnCount();//返回此ResultSet对象中的列数
List<Map<String,Object>>list=newArrayList<Map<String,Object>>();
Map<String,Object>rowData=newHashMap<String,Object>();
while(rs.next()){
rowData=newHashMap<String,Object>(columnCount);
for(inti=1;i<=columnCount;i++){
rowData.put(md.getColumnName(i),rs.getObject(i));
}
list.add(rowData);
}
returnlist;
}
/**
*查询sql语句。
*
*@paramsql
*被执行的sql语句
*@returnList<Map<String,Object>>
*@throwsSQLException
*@author宋立君
*@date2014年07月03日
*/
publicList<Map<String,Object>>query(Stringsql)throwsSQLException{
List<Map<String,Object>>results=null;
Connectionconn=null;
try{
conn=getConnection();
QueryRunnerqr=newQueryRunner();
results=qr.query(conn,sql,newMapListHandler());
}finally{
Close(conn);
}
returnresults;
}
/**
*根据参数查询sql语句
*
*@paramsql
*sql语句
*@paramparam
*参数
*@returnList<Map<String,Object>>
*@throwsSQLException
*@author宋立君
*@date2014年07月03日
*/
publicList<Map<String,Object>>query(Stringsql,Objectparam)
throwsSQLException{
List<Map<String,Object>>results=null;
Connectionconn=null;
try{
conn=getConnection();
QueryRunnerqr=newQueryRunner();
results=(List<Map<String,Object>>)qr.query(conn,sql,param,
newMapListHandler());
}catch(SQLExceptione){
e.printStackTrace();
}finally{
Close(conn);
}
returnresults;
}
/**
*执行sql语句
*
*@paramsql
*被执行的sql语句
*@return受影响的行
*@throwsException
*@author宋立君
*@date2014年07月03日
*/
publicintexecute(Stringsql)throwsException{
Connectionconn=getConnection();
introws=0;
try{
QueryRunnerqr=newQueryRunner();
rows=qr.update(conn,sql);
}finally{
Close(conn);
}
returnrows;
}
/**
*执行含参数的sql语句
*
*@paramsql
*被执行的sql语句
*@paramparams
*参数
*@return返回受影响的行
*@throwsException
*@author宋立君
*@date2014年07月03日
*/
publicintexecute(Stringsql,Object[]params)throwsException{
Connectionconn=getConnection();
introws=0;
try{
QueryRunnerqr=newQueryRunner();
rows=qr.update(conn,sql,params);
}finally{
Close(conn);
}
returnrows;
}
/**
*关闭连接
*
*@paramconn
*@throwsSQLException
*@author宋立君
*@date2014年07月03日
*/
publicvoidClose(Connectionconn)throwsSQLException{
if(conn!=null){
conn.close();
}
DbUtils.closeQuietly(conn);
}
/**
*启动连接池
*
*@author宋立君
*@date2014年07月03日
*/
privatevoidStartPool(){
try{
Class.forName(dri);
}catch(ClassNotFoundExceptione1){
e1.printStackTrace();
}
if(connectionPool!=null){
ShutdownPool();
}
try{
connectionPool=newGenericObjectPool(null);
ConnectionFactoryconnectionFactory=newDriverManagerConnectionFactory(
url,username,password);
PoolableConnectionFactorypoolableConnectionFactory=newPoolableConnectionFactory(
connectionFactory,connectionPool,null,"SELECT1",false,
true);
Class.forName("org.apache.commons.dbcp.PoolingDriver");
PoolingDriverdriver=(PoolingDriver)DriverManager
.getDriver("jdbc:apache:commons:dbcp:");
driver.registerPool(poolName,poolableConnectionFactory.getPool());
}catch(Exceptione){
e.printStackTrace();
}
//开启查询程序
queryThread=newQueryThread(this);
queryThread.start();
}
/**
*关闭连接池
*
*@author宋立君
*@date2014年07月03日
*/
privatevoidShutdownPool(){
try{
PoolingDriverdriver=(PoolingDriver)DriverManager
.getDriver("jdbc:apache:commons:dbcp:");
driver.closePool(poolName);
//关闭定时查询
queryThread.setStartQuery(false);
}catch(SQLExceptione){
e.printStackTrace();
}
}
/**
*得到一个连接
*
*@return
*@author宋立君
*@date2014年07月03日
*/
publicsynchronizedConnectiongetConnection(){
Connectionconn=null;
try{
if(connectionPool==null)
StartPool();
conn=DriverManager.getConnection("jdbc:apache:commons:dbcp:"
+poolName);
}catch(Exceptione){
e.printStackTrace();
}
returnconn;
}
}
/**
*当连接池启动后会自动定时查询数据库,防止数据库连接超时。
*
*@author宋立君
*@date2014年07月03日
*/
classQueryThreadextendsThread{
privateDBUtildbUtil=null;
//是否开启查询
privatebooleanstartQuery=true;
/**
*功能:对应的数据库连接。
*
*@author宋立君
*@date2014年07月03日
*@paramdbUtil
*数据库连接
*/
publicQueryThread(DBUtildbUtil){
this.dbUtil=dbUtil;
}
publicvoidrun(){
while(true){
try{
if(startQuery){
this.dbUtil.query("select1");
}
//System.out.println(startQuery+"123");
}catch(Exceptione){
e.printStackTrace();
}finally{
try{
Thread.sleep(120000);
}catch(InterruptedExceptione){
e.printStackTrace();
}
}
}
}
publicvoidsetStartQuery(booleanstartQuery){
//System.out.println("startQueryshut:"+startQuery);
this.startQuery=startQuery;
}
}