Dependency package download: http://xiazai.VeVB.COm/201407/tools/java-db-dependency(VeVB.COm).rar
Database connection class source code:
package com.itjh.javaUtil;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.ResultSetMetaData;import java.sql.SQLException;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.commons.dbcp.ConnectionFactory;import org.apache.commons.dbcp.DriverManagerConnectionFactory;import org.apache.commons.dbcp.PoolableConnectionFactory;import org.apache.commons.dbcp.PoolingDriver;import org.apache.commons.dbutils.DbUtils;import org.apache.commons.dbutils.QueryRunner;import org.apache.commons.dbutils.handlers.MapListHandler;import org.apache. commons.pool.ObjectPool;import org.apache.commons.pool.impl.GenericObjectPool;/** * Comprehensive class for connecting to the database. </br> * Depends on jar packages: commons.dbcp-1.4, commons.dbutils-1.3, commons.pool-1.5.4 package. * * @author Song Lijun* @date July 3, 2014*/public class DBUtil {private String dri = null;private String url = null;private String username = null;private String password = null;private String poolName = null; // Connection pool name private ObjectPool connectionPool = null; // Connection pool // Corresponding scheduled query class private QueryThread queryThread = null; /** * Function: Constructor * * @author Song Lijun * @date July 3, 2014 * @param dri * Full class name of the driver, for example: com.mysql.jdbc.Driver. * @param url * Database url connection, for example: * "jdbc:mysql://127.0.0.1:3306/test?autoReconnect=true&useUnicode=true&characterEncoding=UTF-8" * @param userName * Database user name, for example: root * @param password * Database password, for example: abc * @param poolName * The name of the created database connection pool, such as mypool. Note that this name cannot be repeated for a web container. */public DBUtil(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 ;}/** * Execute sql. * * @param conn * Connection * @param pstm * PreparedStatement * @return int The affected row corresponding to the execution of sql. * @throws SQLException * @author Song Lijun* @date July 3, 2014*/public int execute(Connection conn, PreparedStatement pstm)throws SQLException {try {return pstm.executeUpdate();} finally {Close(conn);} }/** * Query sql. * * @param conn * Connection * @param pstm * PreparedStatement * @return List<Map<String,Object>> Query result set * @throws SQLException * @author Song Lijun * @date July 3, 2014 */public List <Map<String, Object>> query(Connection conn,PreparedStatement pstm) throws SQLException {try {return resultSetToList(pstm.executeQuery());} finally {Close(conn);}}/** * Function: ResultSet is converted to List<Map<String,Object>> * * * @param rs * ResultSet original data set * @ return List<Map<String,Object>> * @throws java.sql.SQLException * @author Song Lijun* @date July 3, 2014*/private List<Map<String, Object>> resultSetToList(ResultSet rs)throws java.sql.SQLException {if (rs == null)return Collections.EMPTY_LIST;ResultSetMetaData md = rs.getMetaData() ; // Get the structural information of the result set (rs), such as the number of fields, field names, etc. int columnCount = md.getColumnCount(); // Return the number of columns in this ResultSet object List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();Map<String, Object> rowData = new HashMap<String, Object>();while (rs.next()) {rowData = new HashMap<String, Object>(columnCount);for (int i = 1; i <= columnCount; i++) {rowData.put(md.getColumnName(i), rs.getObject(i));}list.add(rowData);}return list;}/** * Query sql statement. * * @param sql * The executed sql statement * @return List<Map<String,Object>> * @throws SQLException * @author Song Lijun* @date July 3, 2014 */public List<Map<String, Object >> query(String sql) throws SQLException {List<Map<String, Object>> results = null;Connection conn = null;try {conn = getConnection();QueryRunner qr = new QueryRunner();results = qr.query(conn, sql, new MapListHandler());} finally {Close(conn);}return results;}/** * Query sql based on parameters statement * * @param sql * sql statement * @param param * parameter * @return List<Map<String,Object>> * @throws SQLException * @author Song Lijun* @date July 3, 2014*/public List<Map<String, Object>> query(String sql, Object param)throws SQLException {List <Map<String, Object>> results = null;Connection conn = null;try {conn = getConnection();QueryRunner qr = new QueryRunner();results = (List<Map<String, Object>>) qr.query(conn, sql, param,new MapListHandler());} catch (SQLException e) {e.printStackTrace();} finally {Close (conn);}return results;}/** * Execute sql statement* * @param sql * The executed sql statement* @return Affected rows* @throws Exception * @author Song Lijun* @date July 3, 2014*/public int execute(String sql) throws Exception {Connection conn = getConnection();int rows = 0;try {QueryRunner qr = new QueryRunner(); rows = qr.update(conn, sql);} finally {Close(conn);}return rows;}/** * Execute the sql statement with parameters* * @param sql * The executed sql statement* @param params * Parameters* @return Return the affected rows* @throws Exception * @author Song Lijun* @date July 3, 2014*/public int execute(String sql, Object[] params) throws Exception {Connection conn = getConnection();int rows = 0;try {QueryRunner qr = new QueryRunner();rows = qr.update(conn, sql, params);} finally {Close(conn);}return rows;}/ ** * Close the connection * * @param conn * @throws SQLException * @author Song Lijun * @date July 3, 2014*/public void Close(Connection conn) throws SQLException {if (conn != null) {conn.close();}DbUtils.closeQuietly(conn);}/** * Start the connection pool* * @author Song Lijun* @date July 3, 2014*/private void StartPool() {try {Class.forName(dri);} catch (ClassNotFoundException e1) {e1.printStackTrace();}if (connectionPool != null) {ShutdownPool();}try {connectionPool = new GenericObjectPool(null);ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, username, password);PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(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();}//Open the query program queryThread = new QueryThread(this);queryThread.start();}/** * Close the connection pool* * @author Song Lijun* @date July 3, 2014*/private void ShutdownPool() {try {PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");driver.closePool(poolName);//Close scheduled query queryThread.setStartQuery(false);} catch (SQLException e) {e.printStackTrace() ;}}/** * Get a connection* * @return * @author Song Lijun* @date July 3, 2014*/public synchronized Connection getConnection() {Connection conn = null;try {if (connectionPool == null)StartPool();conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:"+ poolName);} catch (Exception e) {e.printStackTrace();}return conn;}}/** * When the connection pool is started, it will automatically query the database regularly to prevent the database connection from timing out. * * @author Song Lijun* @date July 3, 2014*/class QueryThread extends Thread {private DBUtil dbUtil = null;//Whether to enable query private boolean startQuery = true;/** * Function: Corresponding database connection. * * @author Song Lijun* @date July 3, 2014* @param dbUtil * Database connection*/public QueryThread(DBUtil dbUtil) {this.dbUtil = dbUtil;}public void run() {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(); }}}}public void setStartQuery(boolean startQuery) {// System.out.println("startQuery shut:"+startQuery);this.startQuery = startQuery;}}