qileilove

          blog已經轉移至github,大家請訪問 http://qaseven.github.io/

          封裝數據庫操作

           今天在一本書上面看到了一個封裝數據庫操作的輔助類,封裝了獲得數據庫的連接、關閉數據庫的連接、執行SQLINSERT/UPDATE/DELETE/SELECT 語句的方法。
            代碼如下:
          /**
          *
          */
          package com.sotaof.struts.db.utils;
          import java.sql.Connection;
          import java.sql.PreparedStatement;
          import java.sql.ResultSet;
          import java.sql.ResultSetMetaData;
          import java.sql.SQLException;
          import java.sql.Statement;
          import java.text.DateFormat;
          import java.util.ArrayList;
          import java.util.Date;
          import java.util.HashMap;
          import java.util.List;
          import java.util.Map;
          import java.util.logging.Logger;
          import javax.naming.InitialContext;
          import javax.sql.DataSource;
          /**
          * @Title: DbUtils.java
          * @Package com.sotaof.struts.db.utils
          * @Description: TODO
          * @author A18ccms A18ccms_gmail_com
          * @date 2013-2-4 下午06:30:36
          * @version V1.0
          */
          public class DbUtils {
          private static Logger logger = Logger.getLogger("DbUtils");
          public static int execute(String sql, List<Object> paramList) throws Exception
          {
          if(sql == null || sql.trim().equals(""))
          {
          logger.info("parameter is valid!");
          }
          Connection conn = null;
          PreparedStatement pstmt = null;
          int result = 0;
          try
          {
          conn = DbUtils.getConnection();
          pstmt = DbUtils.getPreparedStatement(conn, sql);
          setPreparedStatementParam(pstmt, paramList);
          if(pstmt == null)
          {
          return -1;
          }
          result = pstmt.executeUpdate();
          }
          catch(Exception e)
          {
          logger.info(e.getMessage());
          throw new Exception(e);
          }
          finally
          {
          closeStatement(pstmt);
          closeConn(conn);
          }
          return result;
          }
          public static Connection getConnection() throws Exception
          {
          InitialContext cxt = new InitialContext();
          if(cxt == null)
          {
          throw new Exception("no context!");
          }
          DataSource ds = (DataSource) cxt.lookup("java:/comp/env/jdbc/orcl");
          if(ds == null)
          {
          throw new Exception("Data source not found!");
          }
          return ds.getConnection();
          }
          public static PreparedStatement getPreparedStatement(Connection conn, String sql) throws Exception
          {
          if(conn == null || sql == null || sql.trim().equals(""))
          {
          return null;
          }
          PreparedStatement pstmt = conn.prepareStatement(sql.trim());
          return pstmt;
          }
          public static void setPreparedStatementParam(PreparedStatement pstmt, List<Object> paramList) throws Exception
          {
          if(pstmt == null || paramList == null || paramList.isEmpty())
          {
          return;
          }
          DateFormat df = DateFormat.getDateTimeInstance();
          for(int i = 0; i < paramList.size(); i++)
          {
          if(paramList.get(i) instanceof Integer)
          {
          int paramValue = ((Integer) paramList.get(i)).intValue();
          pstmt.setInt(i + 1, paramValue);
          }
          else if(paramList.get(i) instanceof Float)
          {
          float paramValue = ((Float) paramList.get(i)).floatValue();
          pstmt.setFloat(i + 1, paramValue);
          }
          else if(paramList.get(i) instanceof Double)
          {
          double paramValue = ((Double) paramList.get(i)).doubleValue();
          pstmt.setDouble(i + 1, paramValue);
          }
          else if(paramList.get(i) instanceof Date)
          {
          pstmt.setString(i + 1, df.format((Date)paramList.get(i)));
          }
          else if(paramList.get(i) instanceof Long)
          {
          long paramValue = ((Long)paramList.get(i)).longValue();
          pstmt.setLong(i + 1, paramValue);
          }
          else if(paramList.get(i) instanceof String)
          {
          pstmt.setString(i + 1, (String)paramList.get(i));
          }
          }
          return;
          }
          private static void closeConn(Connection conn)
          {
          if(conn == null)
          {
          return;
          }
          try
          {
          conn.close();
          }
          catch(SQLException e)
          {
          logger.info(e.getMessage());
          }
          }
          private static void closeStatement(Statement stmt)
          {
          if(stmt == null)
          {
          return;
          }
          try
          {
          stmt.close();
          }
          catch(SQLException e)
          {
          logger.info(e.getMessage());
          }
          }
          private static void closeResultSet(ResultSet rs)
          {
          if(rs == null)
          {
          return;
          }
          try
          {
          rs.close();
          }
          catch(SQLException e)
          {
          logger.info(e.getMessage());
          }
          }
          private static ResultSet getResultSet(PreparedStatement pstmt) throws Exception
          {
          if(pstmt == null)
          {
          return null;
          }
          ResultSet rs = pstmt.executeQuery();
          return rs;
          }
          public static List<Map<String,String>> getQueryList(String sql, List<Object> paramList) throws Exception
          {
          if(sql == null || sql.trim().equals(""))
          {
          logger.info("parameter is valid!");
          return null;
          }
          Connection conn = null;
          PreparedStatement pstmt = null;
          ResultSet rs = null;
          List<Map<String,String>> queryList = null;
          try
          {
          conn = DbUtils.getConnection();
          pstmt = DbUtils.getPreparedStatement(conn, sql);
          setPreparedStatementParam(pstmt, paramList);
          if(pstmt == null)
          {
          return null;
          }
          rs = DbUtils.getResultSet(pstmt);
          queryList = DbUtils.getQueryList(rs);
          }
          catch(Exception e)
          {
          logger.info(e.getMessage());
          throw new Exception();
          }
          finally
          {
          closeResultSet(rs);
          closeStatement(pstmt);
          closeConn(conn);
          }
          return queryList;
          }
          private static List<Map<String,String>> getQueryList(ResultSet rs) throws Exception
          {
          if(rs == null)
          {
          return null;
          }
          ResultSetMetaData rsMetaData = rs.getMetaData();
          int columnCount = rsMetaData.getColumnCount();
          List<Map<String,String>> dataList = new ArrayList<Map<String,String>>();
          while(rs.next())
          {
          Map<String,String> dataMap = new HashMap<String,String>();
          for(int i = 0; i < columnCount; i++)
          {
          dataMap.put(rsMetaData.getColumnName(i+1), rs.getString(i+1));
          }
          dataList.add(dataMap);
          }
          return dataList;
          }
          }
            不過我認為這種方法雖然封裝性比較好,也比較好管理,但是當出現異常時,對于錯誤的查找非常的麻煩,所以我個人很少使用這樣的方法,不過如果這樣的數據庫麻煩,那么就用Hibernate框架吧(如果你的數據庫夠強大的話)。

          posted on 2014-07-02 16:39 順其自然EVO 閱讀(193) 評論(0)  編輯  收藏 所屬分類: 測試學習專欄

          <2014年7月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          導航

          統計

          常用鏈接

          留言簿(55)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 长顺县| 赤城县| 罗山县| 嘉善县| 林州市| 阳高县| 丹寨县| 仪征市| 广宁县| 廉江市| 江川县| 栾城县| 康保县| 台中县| 大埔县| 聂拉木县| 前郭尔| 朝阳县| 磐石市| 靖安县| 图木舒克市| 新平| 正定县| 高州市| 大安市| 若羌县| 崇信县| 团风县| 邵阳县| 肃宁县| 荆州市| 穆棱市| 盖州市| 克拉玛依市| 城固县| 兴隆县| 嫩江县| 克东县| 鄄城县| 高雄市| 怀柔区|