package com.dangdang.msg.dbutil; import com.dangdang.msg.configure.*; import com.mysql.jdbc.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import org.apache.log4j.Logger; /** * mysql 的数据类,只包含数据库建立,nosql的执行 * * @author 李朋飞 */ public class DBHelper { /** * 获取数据库的连接 * * @return 返回conn, */ public static Logger logger; private static Connection conn = null; public static void getConnection() { logger = Logger.getLogger(DBHelper.class); try { Class.forName(Config.dbConfig.getDbdriver()).newInstance(); // 加载数据库驱动 conn = (Connection) DriverManager.getConnection( Config.dbConfig.getDbhost(), Config.dbConfig.getUser(), Config.dbConfig.getPassword()); conn.setAutoCommit(false); } catch (ClassNotFoundException e) { logger.error("未找到类:" + Config.dbConfig.getDbdriver(), e); } catch (SQLException e) { logger.error("无法连接数据库", e); } catch (Exception e) { logger.error("其他异常", e); } } public static boolean commitJob() { try { conn.commit(); return true; } catch (SQLException e) { logger.error("commit error!"); return false; } } public static Connection getConn() { // 若超时,或者连接中断 if (true == isConnOutTime()) getConnection(); return conn; } /** * 判断数据库连接是否未超时 * isConnection * return boolean true,则未超时,否则超时 */ private static boolean isConnOutTime() { try { // 若未初始化连接,则连接初始化 if (conn == null || conn.isClosed() == true) return true; // ping ,查看是否连接超时 if (conn instanceof com.mysql.jdbc.Connection) { conn.ping(); } } catch (SQLException e) { logger.error("连接超时", e); return true; } return true; } /** * 增删改【Add、Del、Update】 * * @param sql * 需要执行的SQL语句 * @return int 返回是否成功,若失败,则返回-1,若成功,但未修改数据库,则返回0,否则返回正整数 */ public static int executeNonQuery(String sql) throws SQLException { int result = 0; Statement stmt = null; stmt = conn.createStatement(); result = stmt.executeUpdate(sql); return result; } /** * 查询SQL语句,预期结果为一个String数组,返回结果 * * @param sql * 所要执行的sql语句 * @return 返回值为预期结果 * @throws SQLException * SQL执行错误异常 */ public static String getString(String sql) throws SQLException { Statement stmt = null; ResultSet rs = null; String ret = null; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (false == rs.wasNull() && rs.next()) ret = rs.getString(1); return ret; } /** * 查询SQL语句,该SQL语句返回结果包含多行一列,返回该列 * * @param sql * 需要主席邢的sql语句 * @return 返回值为ArrayList * @throws SQLException * 抛出sql异常 */ public static ArrayList<String> getList(String sql) throws SQLException { Statement stmt = null; ResultSet rs = null; ArrayList<String> ret = new ArrayList<String>(); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); if (rs.wasNull()) return null; while (rs.next()) ret.add(rs.getString(1)); return ret; } }