packagecom.dangdang.msg.dbutil;import com.dangdang.msg.configure.*;importcom.mysql.jdbc.Connection;importjava.sql.DriverManager;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.sql.Statement;importjava.util.ArrayList;importorg.apache.log4j.Logger;/*** mysql 的数据类,只包含数据库建立,nosql的执行
*
*@author李朋飞*/
public classDBHelper {/*** 获取数据库的连接
*
*@return返回conn,*/
public staticLogger logger;private static Connection conn = null;public static voidgetConnection() {
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 booleancommitJob() {try{
conn.commit();return true;
}catch(SQLException e) {
logger.error("commit error!");return false;
}
}public staticConnection getConn() {//若超时,或者连接中断
if (true ==isConnOutTime())
getConnection();returnconn;
}/*** 判断数据库连接是否未超时
* isConnection
* return boolean true,则未超时,否则超时*/
private static booleanisConnOutTime() {try{//若未初始化连接,则连接初始化
if (conn == null || conn.isClosed() == true)return true;//ping ,查看是否连接超时
if (conn instanceofcom.mysql.jdbc.Connection) {
conn.ping();
}
}catch(SQLException e) {
logger.error("连接超时", e);return true;
}return true;
}/*** 增删改【Add、Del、Update】
*
*@paramsql
* 需要执行的SQL语句
*@returnint 返回是否成功,若失败,则返回-1,若成功,但未修改数据库,则返回0,否则返回正整数*/
public static int executeNonQuery(String sql) throwsSQLException {int result = 0;
Statement stmt= null;
stmt=conn.createStatement();
result=stmt.executeUpdate(sql);returnresult;
}/*** 查询SQL语句,预期结果为一个String数组,返回结果
*
*@paramsql
* 所要执行的sql语句
*@return返回值为预期结果
*@throwsSQLException
* SQL执行错误异常*/
public static String getString(String sql) throwsSQLException {
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);returnret;
}/*** 查询SQL语句,该SQL语句返回结果包含多行一列,返回该列
*
*@paramsql
* 需要主席邢的sql语句
*@return返回值为ArrayList
*@throwsSQLException
* 抛出sql异常*/
public static ArrayList getList(String sql) throwsSQLException {
Statement stmt= null;
ResultSet rs= null;
ArrayList ret = new ArrayList();
stmt=conn.createStatement();
rs=stmt.executeQuery(sql);if(rs.wasNull())return null;while(rs.next())
ret.add(rs.getString(1));returnret;
}
}