java 连接数据库公共类,java常用工具类之数据库连接类(可以连接多种数据库)...

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;

/**

* 连接数据库的综合类。

* 依赖jar包:commons.dbcp-1.4,commons.dbutils-1.3,commons.pool-1.5.4包。

*

* @author 宋立君

* @date 2014年07月03日

*/

publicclassDBUtil {

privateString dri =null;

privateString url =null;

privateString username =null;

privateString password =null;

privateString poolName =null;// 连接池名称

privateObjectPool connectionPool =null;// 连接池

// 对应的定时查询类

privateQueryThread queryThread =null;

/**

* 功能:构造函数

*

* @author 宋立君

* @date 2014年07月03日

* @param dri

*      驱动全类名,例如:com.mysql.jdbc.Driver。

* @param url

*      数据库url连接,例如:

*      "jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8"

* @param userName

*      数据库用户名,例如:root

* @param password

*      数据库密码,例如:abc

* @param poolName

*      创建的数据库连接池的名称,例如mypool,注意一个web容器此名称不能重复。

*/

publicDBUtil(String dri, String url, String userName, String password,

String poolName) {

this.dri = dri;

this.url = url;

this.username = userName;

this.password = password;

this.poolName = poolName;

}

/**

* 执行sql。

*

* @param conn

*      连接

* @param pstm

*      PreparedStatement

* @return int 执行sql对应的影响行。

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicintexecute(Connection conn, PreparedStatement pstm)

throwsSQLException {

try{

returnpstm.executeUpdate();

} finally{

Close(conn);

}

}

/**

* 查询sql。

*

* @param conn

*      连接

* @param pstm

*      PreparedStatement

* @return List> 查询的结果集

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicList> query(Connection conn,

PreparedStatement pstm) throwsSQLException {

try{

returnresultSetToList(pstm.executeQuery());

} finally{

Close(conn);

}

}

/**

* 功能:ResultSet 转为List>

*

*

* @param rs

*      ResultSet 原始数据集

* @return List>

* @throws java.sql.SQLException

* @author 宋立君

* @date 2014年07月03日

*/

privateList> resultSetToList(ResultSet rs)

throwsjava.sql.SQLException {

if(rs ==null)

returnCollections.EMPTY_LIST;

ResultSetMetaData md = rs.getMetaData(); // 得到结果集(rs)的结构信息,比如字段数、字段名等

intcolumnCount = md.getColumnCount();// 返回此 ResultSet 对象中的列数

List> list = newArrayList>();

Map rowData = newHashMap();

while(rs.next()) {

rowData = newHashMap(columnCount);

for(inti = 1; i <= columnCount; i++) {

rowData.put(md.getColumnName(i), rs.getObject(i));

}

list.add(rowData);

}

returnlist;

}

/**

* 查询sql语句。

*

* @param sql

*      被执行的sql语句

* @return List>

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicList> query(String sql)throwsSQLException {

List> results = null;

Connection conn = null;

try{

conn = getConnection();

QueryRunner qr = newQueryRunner();

results = qr.query(conn, sql, newMapListHandler());

} finally{

Close(conn);

}

returnresults;

}

/**

* 根据参数查询sql语句

*

* @param sql

*      sql语句

* @param param

*      参数

* @return List>

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicList> query(String sql, Object param)

throwsSQLException {

List> results = null;

Connection conn = null;

try{

conn = getConnection();

QueryRunner qr = newQueryRunner();

results = (List>) qr.query(conn, sql, param,

newMapListHandler());

} catch(SQLException e) {

e.printStackTrace();

} finally{

Close(conn);

}

returnresults;

}

/**

* 执行sql语句

*

* @param sql

*      被执行的sql语句

* @return 受影响的行

* @throws Exception

* @author 宋立君

* @date 2014年07月03日

*/

publicintexecute(String sql)throwsException {

Connection conn = getConnection();

introws = 0;

try{

QueryRunner qr = newQueryRunner();

rows = qr.update(conn, sql);

} finally{

Close(conn);

}

returnrows;

}

/**

* 执行含参数的sql语句

*

* @param sql

*      被执行的sql语句

* @param params

*      参数

* @return 返回受影响的行

* @throws Exception

* @author 宋立君

* @date 2014年07月03日

*/

publicintexecute(String sql, Object[] params)throwsException {

Connection conn = getConnection();

introws = 0;

try{

QueryRunner qr = newQueryRunner();

rows = qr.update(conn, sql, params);

} finally{

Close(conn);

}

returnrows;

}

/**

* 关闭连接

*

* @param conn

* @throws SQLException

* @author 宋立君

* @date 2014年07月03日

*/

publicvoidClose(Connection conn)throwsSQLException {

if(conn !=null) {

conn.close();

}

DbUtils.closeQuietly(conn);

}

/**

* 启动连接池

*

* @author 宋立君

* @date 2014年07月03日

*/

privatevoidStartPool() {

try{

Class.forName(dri);

} catch(ClassNotFoundException e1) {

e1.printStackTrace();

}

if(connectionPool !=null) {

ShutdownPool();

}

try{

connectionPool = newGenericObjectPool(null);

ConnectionFactory connectionFactory = newDriverManagerConnectionFactory(

url, username, password);

PoolableConnectionFactory poolableConnectionFactory = newPoolableConnectionFactory(

connectionFactory, connectionPool, null,"SELECT 1",false,

true);

Class.forName("org.apache.commons.dbcp.PoolingDriver");

PoolingDriver driver = (PoolingDriver) DriverManager

.getDriver("jdbc:apache:commons:dbcp:");

driver.registerPool(poolName, poolableConnectionFactory.getPool());

} catch(Exception e) {

e.printStackTrace();

}

// 开启查询程序

queryThread = newQueryThread(this);

queryThread.start();

}

/**

* 关闭连接池

*

* @author 宋立君

* @date 2014年07月03日

*/

privatevoidShutdownPool() {

try{

PoolingDriver driver = (PoolingDriver) DriverManager

.getDriver("jdbc:apache:commons:dbcp:");

driver.closePool(poolName);

// 关闭定时查询

queryThread.setStartQuery(false);

} catch(SQLException e) {

e.printStackTrace();

}

}

/**

* 得到一个连接

*

* @return

* @author 宋立君

* @date 2014年07月03日

*/

publicsynchronizedConnection getConnection() {

Connection conn = null;

try{

if(connectionPool ==null)

StartPool();

conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:"

+ poolName);

} catch(Exception e) {

e.printStackTrace();

}

returnconn;

}

}

/**

* 当连接池启动后会自动定时查询数据库,防止数据库连接超时。

*

* @author 宋立君

* @date 2014年07月03日

*/

classQueryThreadextendsThread {

privateDBUtil dbUtil =null;

// 是否开启查询

privatebooleanstartQuery =true;

/**

* 功能:对应的数据库连接。

*

* @author 宋立君

* @date 2014年07月03日

* @param dbUtil

*      数据库连接

*/

publicQueryThread(DBUtil dbUtil) {

this.dbUtil = dbUtil;

}

publicvoidrun() {

while(true) {

try{

if(startQuery) {

this.dbUtil.query("select 1");

}

// System.out.println(startQuery+"  123");

} catch(Exception e) {

e.printStackTrace();

} finally{

try{

Thread.sleep(120000);

} catch(InterruptedException e) {

e.printStackTrace();

}

}

}

}

publicvoidsetStartQuery(booleanstartQuery) {

// System.out.println("startQuery shut:"+startQuery);

this.startQuery = startQuery;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package com.hexiang.utils.dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; import org.apache.log4j.Logger; public class DBConnection { /** * 获得与数据库连接 * * @param path * @return Connection */ public static Connection getConn(String classDriver, String url, String user, String pwd) { try { Class.forName(classDriver); return DriverManager.getConnection(url, user, pwd); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(DataSource dataSource) { try { return dataSource.getConnection(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(String jndiName) { try { Context ctx; ctx = new InitialContext(); DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/" + jndiName); return dataSource.getConnection(); } catch (NamingException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } public static Connection getConn(Properties properties) { try { String driver = properties.getProperty("jdbc.driverClassName"); String url = properties.getProperty("jdbc.url"); String user = properties.getProperty("jdbc.username"); String password = properties.getProperty("jdbc.password"); Class.forName(driver); return DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException ex) { ex.printStackTrace(); } catch (SQLException ex) { ex.printStackTrace(); } return null; } /** * oracle连接 * * @param path * @return Connection */ public static Connection getOracleConn(String
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值