tbwshc

          java 數據庫通用操作類

          package com.hospital.dao.tools;
           
          import java.sql.CallableStatement;
          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.sql.Statement;
          import java.sql.Types;
          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.Iterator;
          import org.apache.log4j.Logger;
           
          /**
           * 數據庫操作管理類
           * 
           * @author Harlyhood
           * 
           */
          public class DBManager {
           
              // --------------------------------------------------------- Instance
              private static Logger logger = Logger.getLogger(DBManager.class);
              // --------------------------------------------------------- Methods
           
              // 數據庫連接對象
              private Connection con;
              // SQL語句對象
              private Statement stmt;
              // 帶參數的Sql語句對象
              private PreparedStatement pstmt;
              // 記錄集對象
              private ResultSet rs;
              // 數據連接管理(連接池對象)
              private DBConnectionManager dcm = null;
           
              /** ***********************手動設置的連接參數********************************* */
              @SuppressWarnings("unused")
              private static String _DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";
              @SuppressWarnings("unused")
              private static String _URL = "jdbc:sqlserver://localhost:1433;database=Hospital_AI_DB;characterEncoding=gb2312";
              @SuppressWarnings("unused")
              private static String _USER_NA = "sa";
              @SuppressWarnings("unused")
              private static String _PASSWORD = "";
           
              /** ********************************************************************** */
           
              // 默認構造
              public DBManager() {
              }
           
              /** ****************************************************************************************** */
              /**
               * **************************************** 數據庫連接初始化
               * ***********************************
               */
              /** ****************************************************************************************** */
           
              /**
               * 得到一個默認的數據庫連接[從 com.hospital.dao.tools.db.properties文件初始化]
               * 
               * @throws Exception
               */
              private void getConnection() {
                  logger.info("###############open:::::從默認的配置文件得到一個數據庫連接");
                  // 獲取一個連接tb池管理類的實例
                  dcm = DBConnectionManager.getInstance();
                  // 得到一個數據庫連接
                  con = dcm.getConnection("mysql");
           
                  try {
                      con.setAutoCommit(false);
                  } catch (SQLException e) {
           
                      e.printStackTrace();
                  }
              }
           
              /**
               * 從指定參數得到一個連接對象
               * 
               * @param driver
               * @param url
               * @param user_na
               * @param password
               * @throws Exception
               */
              public void getConnection(String driver, String url, String user_na,
                      String password) throws Exception {
                  try {
                      logger.info("###############open:::::從指定配置中得到一個數據庫連接");
                      Class.forName(driver);
                      con = DriverManager.getConnection(url, user_na, password);
                  } catch (ClassNotFoundException ex) {
                      logger
                              .info("###############Error[com.hospital.dao.tools.DBManager^^^Method:getConnection^^^Line:81]找不到類驅動類: "
                                      + driver);
                      throw ex;
                  } catch (SQLException ex) {
                      logger
                              .info("###############Error[com.hospital.dao.tools.DBManager^^^Method:getConnection^^^Line:81]加載類: "
                                      + driver + " 時出現 SQLException 異常");
                      throw ex;
                  }
              }
           
              /** ****************************************************************************************** */
              /**
               * **************************************** 數據庫操作方法
               * ***********************************
               */
              /** ****************************************************************************************** */
           
              /**
               * 執行SQL語句操作(更新數據 無參數)
               * 
               * @param strSql
               *            SQL語句
               * @throws Exception
               */
              public boolean executeUpdate(String strSql) throws SQLException {
                  getConnection();
                  // getConnection(_DRIVER,_URL,_USER_NA,_PASSWORD);
                  boolean flag = false;
                  stmt = con.createStatement();
                  logger.info("###############::執行SQL語句操作(更新數據 無參數):" + strSql);
                  try {
                      if (0 < stmt.executeUpdate(strSql)) {
                          close_DB_Object();
                          flag = true;
                          con.commit();
                      }
                  } catch (SQLException ex) {
                      logger
                              .info("###############Error DBManager Line126::執行SQL語句操作(更新數據 無參數):"
                                      + strSql + "失敗!");
                      flag = false;
                      con.rollback();
                      throw ex;
                  }
                  return flag;
           
              }
           
              /**
               * 執行SQL語句操作(更新數據 有參數)
               * 
               * @param strSql
               *            sql指令
               * @param prams
               *            參數列表
               * @return
               * @throws SQLException
               */
              public boolean executeUpdate(String strSql, HashMap<Integer, Object> prams)
                      throws SQLException, ClassNotFoundException {
                  getConnection();
                  // getConnection(_DRIVER,_URL,_USER_NA,_PASSWORD);
                  boolean flag = false;
                  try {
                      pstmt = con.prepareStatement(strSql);
                      setParamet(pstmt, prams);
                      logger.info("###############::執行SQL語句操作(更新數據 有參數):" + strSql);
           
                      if (0 < pstmt.executeUpdate()) {
                          close_DB_Object();
                          flag = true;
                          con.commit();
                      }
                  } catch (SQLException ex) {
                      logger
                              .info("###############Error DBManager Line121::執行SQL語句操作(更新數據 無參數):"
                                      + strSql + "失敗!");
                      flag = false;
                      con.rollback();
                      throw ex;
                  } catch (ClassNotFoundException ex) {
                      logger
                              .info("###############Error DBManager Line152::執行SQL語句操作(更新數據 無參數):"
                                      + strSql + "失敗! 參數設置類型錯誤!");
                      con.rollback();
                      throw ex;
                  }
                  return flag;
           
              }
           
              /**
               * 執行SQL語句操作(查詢數據 無參數)
               * 
               * @param strSql
               *            SQL語句
               * @return 數組對象列表
               * @throws Exception
               */
              public ArrayList<HashMap<Object, Object>> executeSql(String strSql)
                      throws Exception {
                  getConnection();
                  // getConnection(_DRIVER,_URL,_USER_NA,_PASSWORD);
                  stmt = con.createStatement();
                  logger.info("###############::執行SQL語句操作(查詢數據):" + strSql);
                  rs = stmt.executeQuery(strSql);
                  con.commit();
                  if (null != rs) {
                      return convertResultSetToArrayList(rs);
                  }
                  close_DB_Object();
                  return null;
              }
           
              /**
               * 執行SQL語句操作(查詢數據 有參數)
               * 
               * @param strSql
               *            SQL語句
               * @param prams
               *            參數列表
               * @return 數組對象列表
               * @throws Exception
               */
              public ArrayList<HashMap<Object, Object>> executeSql(String strSql,
                      HashMap<Integer, Object> prams) throws Exception {
                  getConnection();
                  // getConnection(_DRIVER,_URL,_USER_NA,_PASSWORD);
                  pstmt = con.prepareStatement(strSql);
                  setParamet(pstmt, prams);
                  logger.info("###############::執行SQL語句操作(查詢數據):" + strSql);
                  rs = pstmt.executeQuery();
                  con.commit();
                  if (null != rs) {
                      return convertResultSetToArrayList(rs);
                  }
                  return null;
              }
           
              /**
               * 執行存儲過程(查詢數據 無參數)
               * 
               * @param procName
               *            存儲過程名稱
               * @return 數組列表對象
               * @throws Exception
               */
              public ArrayList<HashMap<Object, Object>> executeProcedureQuery(
                      String procName) throws Exception {
                  getConnection();// 獲取連接
                  String callStr = "{call " + procName + "}";// 構造執行存儲過程的sql指令
                  CallableStatement cs = con.prepareCall(callStr);
                  logger.info("###############::執行存儲過程(查詢數據):" + procName);
                  rs = cs.executeQuery();
                  con.commit();
                  cs.close();
                  close_DB_Object();
                  return convertResultSetToArrayList(rs);
              }
           
              /**
               * 執行存儲過程(查詢數據,帶參數)返回結果集合
               * 
               * @param procName
               *            存儲過程名稱
               * @param parameters
               *            參數對象數組
               * @param al
               *            數組列表對象
               * @return 數組列表對象
               * @throws Exception
               */
              public ArrayList<HashMap<Object, Object>> executeProcedureQuery(
                      String procName, Object[] parameters) throws Exception {
                  int parameterPoint = 0;
                  // 獲取存儲過程信息列表集合
                  ArrayList<HashMap<Object, Object>> procedureInfo = getProcedureInfo(procName);
                  // 獲取存儲過程的完全名稱
                  String procedureCallName = getProcedureCallName(procName,parameters.length);
                  // 獲取連接對象
                  getConnection();
                  // 初始化 存儲過程 執行對象
                  CallableStatement cs = con.prepareCall(procedureCallName);
                  // 參數下標變量
                  int index = 0;
                  // 獲取 存儲過程信息列表集合的 迭代器 對象
                  Iterator<HashMap<Object, Object>> iter = procedureInfo.iterator();
                  // 遍歷存儲過程信息列表集合
                  while (iter.hasNext()) {
                      HashMap<Object, Object> hm = iter.next();
           
                      parameterPoint++;
                      // 如果參數是輸入參數 way = 0
                      if (hm.get("WAY").equals("0")) {
                          // 設置參數到cs
                          cs.setObject(parameterPoint, parameters[index]);
                          // 參數下標+1
                          index++;
                      }
                  }
                  // 釋放這個對象,做為第二次使用
                  procedureInfo = null;
                  logger.info("###############::執行存儲過程(查詢數據):::::" + procedureCallName);
                  rs = cs.executeQuery();
                  con.commit();
                  procedureInfo = convertResultSetToArrayList(rs);
                  cs.close();
                  close_DB_Object();
                  return procedureInfo;
           
              }
           
              /**
               * 執行存儲過程(更新,查詢數據[簡單查詢、非紀錄集],返回輸出參數[非紀錄集])
               * 
               * @param procName
               *            存儲過程名稱
               * @param parameters
               *            參數對象數組
               * @param os
               *            輸出參數對象數組
               * @return 輸出參數對象數組
               * @throws Exception
               */
              public Object[] executeProcedureUpdate(String procName, Object[] parameters)
                      throws Exception {
                  logger.info("------------------------------------------------------------------------------------------------------");
                  logger.info(" Run --> executeProcedureUpdate ##############   正在執行 存儲過程: " + procName +"   ##############");
                  CallableStatement cs = null;
                  Object []returnVal = null;
                  try {
                  // 獲取 存儲過程 調用全名
                  String fullPCallName = getProcedureCallName(procName,parameters.length);
                  logger.info(" Run --> executeProcedureUpdate #   存儲過程命令: " + fullPCallName +"   #");
                  //獲取存儲過程參數信息
                  ArrayList<HashMap<Object, Object>> p_Call_Info_List = getProcedureInfo(procName);
                  //獲取連接
                  getConnection();
                  //創建 存儲過程 執行對象
                  cs = con.prepareCall(fullPCallName);
                  //數組下標
                  int index = 1;
                  //輸出參數下標 紀錄
                  ArrayList<Integer> outPutIndexList = new ArrayList<Integer>();
                  logger.info(" Run --> executeProcedureUpdate #   參數個數是: " + parameters.length +"   #");
                  for(HashMap<Object,Object> tempHash:p_Call_Info_List)
                  {
                      if("0".equals(tempHash.get("WAY")))
                      {
                          //設置輸入參數
                          cs.setObject(index, parameters[index-1]);
                          logger.info(" Run --> executeProcedureUpdate #   輸入 Input: 編號:" + index +" 值: "+parameters[index-1]+" 類型: "+parameters[index-1].getClass()+"   #");
                      }
                      else
                      {
                          //注冊輸出參數
                          cs.registerOutParameter(index, getDataType(tempHash.get("TYPENAME").toString()));
                          //紀錄輸出參數的下標
                          outPutIndexList.add(index);
                          logger.info(" Run --> executeProcedureUpdate #   輸出 OutPut: 編號:" + index +" 值: "+parameters[index-1]+" 類型: "+parameters[index-1].getClass()+"   #");
                      }
                      index++;
                  }
                  logger.info(" Run --> executeProcedureUpdate #   參數設置完畢,正在執行中  :   #");
                   
                  //-------------------- 執行 -----------------
                  if(!cs.execute())
                  {
                      returnVal = new Object[outPutIndexList.size()];
                      logger.info(" Run --> executeProcedureUpdate #   執行成功! :   #");
                      //取輸 出參數的 返回值
                      for(int i = 0 ;i<outPutIndexList.size();i++)
                      {
                          returnVal[i] = cs.getObject(outPutIndexList.get(i));
                          logger.info(" Run --> executeProcedureUpdate #   返回值 "+(i+1)+" "+returnVal[i]+"   #");
                      }
                      con.commit();//提交
                  }
                  } catch (Exception e) {
                      logger.info(" Run --> executeProcedureUpdate #   執行失敗!事務回滾中 :   #");
                      con.rollback();
                      throw e;
                  } 
                  logger.info("------------------------------------------------------------------------------------------------------");
                  return returnVal;
              }
           
              /** ****************************************************************************************** */
              /**
               * ********************************* 小工具
               * ************************************************
               */
              /** ****************************************************************************************** */
           
              /**
               * 關閉數據對象
               */
              public void close_DB_Object() {
                  logger.info("###############close:::::關閉連接對象,語句對象,記錄集對象");
                  if (null != rs) {
                      try {
                          rs.close();
                      } catch (SQLException ex) {
                          rs = null;
                      }
                  }
                  if (null != stmt) {
                      try {
                          stmt.close();
                      } catch (SQLException ex) {
                          stmt = null;
                      }
                  }
                  if (null != pstmt) {
                      try {
                          pstmt.close();
                      } catch (SQLException ex) {
                          pstmt = null;
                      }
                  }
                  if (con != null) {
                      dcm.freeConnection("mysql", con);
                  }
              }
           
           
              /**
               * 設置Sql 指令參數
               * 
               * @param p_stmt
               *            PreparedStatement
               * @param pramets
               *            HashMap
               */
              private PreparedStatement setParamet(PreparedStatement p_stmt,
                      HashMap<Integer, Object> pramets) throws ClassNotFoundException,
                      SQLException {
                  // 如果參數為空
                  if (null != pramets) {
                      // 如果參數個數為0
                      if (0 <= pramets.size()) {
                          for (int i = 1; i <= pramets.size(); i++) {
                              try {
                                  // 字符類型 String
                                  if (pramets.get(i).getClass() == Class
                                          .forName("java.lang.String")) {
                                      p_stmt.setString(i, pramets.get(i).toString());
                                  }
                                  // 日期類型 Date
                                  if (pramets.get(i).getClass() == Class
                                          .forName("java.sql.Date")) {
                                      p_stmt.setDate(i, java.sql.Date.valueOf(pramets
                                              .get(i).toString()));
                                  }
                                  // 布爾類型 Boolean
                                  if (pramets.get(i).getClass() == Class
                                          .forName("java.lang.Boolean")) {
                                      p_stmt.setBoolean(i, (Boolean) (pramets.get(i)));
                                  }
                                  // 整型 int
                                  if (pramets.get(i).getClass() == Class
                                          .forName("java.lang.Integer")) {
                                      p_stmt.setInt(i, (Integer) pramets.get(i));
                                  }
                                  // 浮點 float
                                  if (pramets.get(i).getClass() == Class
                                          .forName("java.lang.Float")) {
                                      p_stmt.setFloat(i, (Float) pramets.get(i));
                                  }
                                  // 雙精度型 double
                                  if (pramets.get(i).getClass() == Class
                                          .forName("java.lang.Double")) {
                                      p_stmt.setDouble(i, (Double) pramets.get(i));
                                  }
           
                              } catch (ClassNotFoundException ex) {
                                  throw ex;
                              } catch (SQLException ex) {
                                  throw ex;
                              }
                          }
                      }
                  }
                  return p_stmt;
              }
           
              /**
               * 轉換記錄集對象為數組列表對象
               * 
               * @param rs
               *            紀錄集合對象
               * @return 數組列表對象
               * @throws Exception
               */
              private ArrayList<HashMap<Object, Object>> convertResultSetToArrayList(
                      ResultSet rs) throws Exception {
                  logger.info("###############::轉換記錄集對象為數組列表對象");
                  // 獲取rs 集合信息對象
                  ResultSetMetaData rsmd = rs.getMetaData();
                  // 創建數組列表集合對象
                  ArrayList<HashMap<Object, Object>> tempList = new ArrayList<HashMap<Object, Object>>();
                  HashMap<Object, Object> tempHash = null;
                  // 填充數組列表集合
                  while (rs.next()) {
                      // 創建鍵值對集合對象
                      tempHash = new HashMap<Object, Object>();
                      for (int i = 0; i < rsmd.getColumnCount(); i++) {
                          // 遍歷每列數據,以鍵值形式存在對象tempHash中
                          tempHash.put(rsmd.getColumnName(i + 1).toUpperCase(), rs
                                  .getString(rsmd.getColumnName(i + 1)));
                      }
                      // 第一個鍵值對,存儲在tempList列表集合對象中
                      tempList.add(tempHash);
                  }
                  close_DB_Object();// 關閉相關鏈接
                  return tempList;// 返回填充完畢的數組列表集合對象
              }
           
              /**
               * 從數據庫得到tb存儲過程信息
               * 
               * @param procName
               *            存儲過程名稱
               * @return 數組列表對象
               * @throws Exception
               */
              private ArrayList<HashMap<Object, Object>> getProcedureInfo(String procName)
                      throws Exception {
                  return this.executeSql("select Syscolumns.isoutparam as Way,systypes.name as TypeName from sysobjects,syscolumns,systypes where systypes.xtype=syscolumns.xtype and syscolumns.id=sysobjects.id and sysobjects.name='"
                          + procName + "' order by Syscolumns.isoutparam");
              }
           
              /**
               * 從數據庫得到存儲過程參數個數
               * 
               * @param procName
               *            存儲過程名稱
               * @return 數組列表對象
               * @throws Exception
               */
              @SuppressWarnings("unused")
              private int getParametersCount(String procName) throws Exception {
                  int returnVal = 0;
                  for (HashMap<Object, Object> tempHas : this
                          .executeSql("select count(*) as RowsCount from sysobjects,syscolumns,systypes where systypes.xtype=syscolumns.xtype and syscolumns.id=sysobjects.id and sysobjects.name='"
                                  + procName + "'")) {
                      returnVal = Integer.parseInt(tempHas.get("ROWSCOUNT").toString());
                  }
                  return returnVal;
              }
           
              /**
               * 得到調用存儲過程的全名
               * 
               * @param procName
               *            存儲過程名稱
               * @return 調用存儲過程的全名
               * @throws Exception
               */
              private String getProcedureCallName(String procName, int prametCount)
                      throws Exception {
                  String procedureCallName = "{call " + procName;
                  for (int i = 0; i < prametCount; i++) {
                      if (0 == i) {
                          procedureCallName = procedureCallName + "(?";
                      }
                      if (0 != i) {
                          procedureCallName = procedureCallName + ",?";
                      }
                  }
                  procedureCallName = procedureCallName + ")}";
                  return procedureCallName;
              }
           
              /**
               * 得到數據類型的整型值
               * 
               * @param typeName
               *            類型名稱
               * @return 數據類型的整型值
               */
              private int getDataType(String typeName) {
                  if (typeName.equals("varchar"))
                      return Types.VARCHAR;
                  if (typeName.equals("int"))
                      return Types.INTEGER;
                  if (typeName.equals("bit"))
                      return Types.BIT;
                  if (typeName.equals("float"))
                      return Types.FLOAT;
                  return 0;
              }
           
              // 設置驅動路徑
              @SuppressWarnings("static-access")
              public void set_DRIVER(String _DRIVER) {
                  this._DRIVER = _DRIVER;
              }
           
              // 設置數據庫密碼
              @SuppressWarnings("static-access")
              public void set_PASSWORD(String _PASSWORD) {
                  this._PASSWORD = _PASSWORD;
              }
           
              // 設置數據庫連接字符串
              @SuppressWarnings("static-access")
              public void set_URL(String _URL) {
                  this._URL = _URL;
              }
           
              // 設置數據庫用戶名
              @SuppressWarnings("static-access")
              public void set_USER_NA(String _USER_NA) {
                  this._USER_NA = _USER_NA;
              }
           
          }

           

          posted on 2013-05-27 16:55 chen11-1 閱讀(504) 評論(0)  編輯  收藏 所屬分類: 隨筆

          主站蜘蛛池模板: 岳普湖县| 台江县| 都江堰市| 通道| 通江县| 涟源市| 洛浦县| 平乐县| 盈江县| 林周县| 铁岭县| 綦江县| 鹤山市| 蒙自县| 油尖旺区| 缙云县| 龙游县| 庆城县| 电白县| 安吉县| 突泉县| 印江| 荔波县| 汤原县| 丰都县| 鄂伦春自治旗| 沅陵县| 龙南县| 吴堡县| 滨海县| 桐梓县| 玉龙| 新巴尔虎右旗| 桓仁| 漳浦县| 分宜县| 吴江市| 尤溪县| 辽阳县| 呼玛县| 昔阳县|