创建BaseDao类使用ConnectionPool连接池
package com.cnhtc.db.dao;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import com.cnhtc.db.tools.DbType;public class BaseDao {private Connection conn = null; // 数据库连接变量private PreparedStatement preparedStatement = null; // 预定义Statement变量private ConnectionPool connectionPool = null; // 连接池管理变量private ResultSet resultSet = null;// 查询的结果public BaseDao() {// TODO Auto-generated constructor stub}// 初始化连接池并建立连接private void init() {// 初始化连接池connectionPool = new ConnectionPool(DbType.DB_DRIVER, DbType.DB_URL,DbType.DB_USERNAME, DbType.DB_PASSWORD);System.out.println("--baseDao-->" + "获得连接池");try {connectionPool.creatPool();conn = connectionPool.getConnection();System.out.println("--baseDao-->" + "获得数据连接");} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}/** * 查询语句 * * @param sql * 无参数查询 * @return resultset结果集 */public ResultSet query(String sql) {init();if (conn == null) {return null;}try {preparedStatement = conn.prepareStatement(sql);resultSet = preparedStatement.executeQuery();return resultSet;} catch (SQLException e) {e.printStackTrace();}return null;}/** * 查询sql语句 * * @param sql * fg.select * from userinfo where id = ? and username = ? * @param param * 对应的参数 * @return resultset集合 */public ResultSet query(String sql, String[] param) {init();if (conn == null) {return null;}try {conn = connectionPool.getConnection();preparedStatement = conn.prepareStatement(sql);if (param != null) {for (int i = 0; i < param.length; i++) {preparedStatement.setString(i + 1, param[i]);}}resultSet = preparedStatement.executeQuery();return resultSet;} catch (SQLException e) {e.printStackTrace();}return null;}/** * 更新sql * * @param sql * @return 更新的行数 */public int update(String sql) {init();if (conn == null) {return -1;}try {preparedStatement = conn.prepareStatement(sql);return preparedStatement.executeUpdate();} catch (Exception e) {e.printStackTrace();}return -1;}/** * 更新带参数的sql语句 * * @param sql * update table set col = ? where id = ? * @param param * @return 影响的行数 */public int update(String sql, String[] param) {init();if (conn == null) {return -1;}try {preparedStatement = conn.prepareStatement(sql);if (param != null) {for (int i = 0; i < param.length; i++) {preparedStatement.setString(i + 1, param[i]);}}return preparedStatement.executeUpdate();} catch (Exception e) {e.printStackTrace();}return -1;}public void closeAll() {try {if(preparedStatement!=null){preparedStatement.close();}if(conn!=null){conn.close();}if(connectionPool!=null){connectionPool.refreshConncetions();}} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}