通過泛型插入(更新)實體數據

經過長時間的。net開發,發現每次操作數據這塊,很繁瑣,要麼是直接拼接sql語句,要麼是利用實體類,但是還是需要拼接sql語句,如何找到一個能減少拼接sql語句的並且還能用到實體類數據的方法呢,我在一直摸索。於是得出了一下方法:、

 

 

現舉例示範代碼如下,當然我覺得還可以改進(比如重複的地方還可以寫成公共方法進行調用)。

  1. /// <summary>   
  2. /// 通過泛型插入數據   
  3. /// </summary>   
  4. /// <typeparam name="T">類名稱</typeparam>   
  5. /// <param name="obj">類對象,如果要插入空值,請使用@NULL</param>   
  6. /// <returns>插入的新記錄ID</returns>   
  7. public static int Insert<T>(T obj)   
  8. {   
  9.   
  10.       StringBuilder strSQL = new StringBuilder();   
  11.   
  12.       strSQL = GetInsertSQL(obj);   
  13.   
  14.       // 插入到數據庫中   
  15.       object result = SQLPlus.ExecuteScalar(CommandType.Text, strSQL, null);   
  16.   
  17.       return Convert.IsDBNull(result) ? 0 : Convert.ToInt32(result);   
  18. }   
  19.   
  20. /// <summary>   
  21. /// 通過泛型更新數據   
  22. /// </summary>   
  23. /// <typeparam name="T">類名稱</typeparam>   
  24. /// <param name="obj">類對象,如果要更新空值,請使用@NULL</param>   
  25. /// <returns>更新結果,大於0爲更新成功</returns>   
  26. public static int Update<T>(T obj)   
  27. {   
  28.   
  29.      StringBuilder strSQL = new StringBuilder();   
  30.      strSQL = GetUpdateSQL(obj);   
  31.   
  32.      if (String.IsNullOrEmpty(strSQL.ToString()))   
  33.      {   
  34.           return 0;   
  35.      }   
  36.   
  37.   
  38.      // 更新到數據庫中   
  39.      object result = SQLPlus.ExecuteNonQuery(CommandType.Text, strSQL, null);   
  40.   
  41.      int returnValue = Convert.IsDBNull(result) ? 0 : Convert.ToInt32(result);   
  42.   
  43.      return returnValue;   
  44.   
  45. }   
  46.   
  47. /// <summary>   
  48. /// 獲取實體的插入語句   
  49. /// </summary>   
  50. /// <typeparam name="T">泛型</typeparam>   
  51. /// <param name="obj">實體對象</param>   
  52. /// <returns>返回插入語句</returns>   
  53. public static StringBuilder GetInsertSQL<T>(T obj)   
  54. {   
  55.   
  56.       string tableKey = GetPropertyValue(obj, BaseSet.PrimaryKey);   
  57.       string keyValue = GetPropertyValue(obj, tableKey);   
  58.       string tableName = GetPropertyValue(obj, BaseSet.TableName);   
  59.   
  60.       Type t = obj.GetType();//獲得該類的Type   
  61.   
  62.       StringBuilder strSQL = new StringBuilder();   
  63.   
  64.       strSQL.Append("insert into " + tableName + "(");   
  65.   
  66.       string fields = "";   
  67.       string values = "";   
  68.   
  69.       //再用Type.GetProperties獲得PropertyInfo[]   
  70.       foreach (PropertyInfo pi in t.GetProperties())   
  71.       {   
  72.   
  73.            object name = pi.Name;//用pi.GetValue獲得值   
  74.   
  75.            // 替換Sql注入符   
  76.            string value1 = Convert.ToString(pi.GetValue(obj, null)).Replace("'""''");   
  77.   
  78.            //string dataType = pi.PropertyType.ToString().ToLower();   
  79.   
  80.            string properName = name.ToString().ToLower();   
  81.   
  82.            if (!string.IsNullOrEmpty(value1) && properName != tableKey.ToLower() && properName != BaseSet.PrimaryKey.ToLower() && properName != BaseSet.TableName.ToLower() && value1 != BaseSet.DateTimeLongNull && value1 != BaseSet.DateTimeShortNull)   
  83.            {   
  84.                 // 判斷是否爲空   
  85.                 if (value1 == BaseSet.NULL)   
  86.                 {   
  87.                     value1 = "";   
  88.                 }   
  89.   
  90.                 fields += Convert.ToString(name) + ",";   
  91.                 values += "'" + value1 + "',";   
  92.   
  93.            }   
  94.   
  95.        }   
  96.   
  97.        // 去掉最後一個,   
  98.        fields = fields.TrimEnd(',');   
  99.        values = values.TrimEnd(',');   
  100.   
  101.        // 拼接Sql串   
  102.        strSQL.Append(fields);   
  103.        strSQL.Append(") values (");   
  104.        strSQL.Append(values);   
  105.        strSQL.Append(")");   
  106.   
  107.        strSQL.Append(";SELECT @@IDENTITY;");   
  108.   
  109.        return strSQL;   
  110. }   
  111.   
  112. /// <summary>   
  113. /// 獲取實體的更新SQL串   
  114. /// </summary>   
  115. /// <typeparam name="T">泛型</typeparam>   
  116. /// <param name="obj">實體對象</param>   
  117. /// <returns>返回插入語句</returns>   
  118. private static StringBuilder GetUpdateSQL<T>(T obj)   
  119. {   
  120.   
  121.      string tableKey = GetPropertyValue(obj, BaseSet.PrimaryKey);   
  122.      string keyValue = GetPropertyValue(obj, tableKey);   
  123.      string tableName = GetPropertyValue(obj, BaseSet.TableName);   
  124.      StringBuilder strSQL = new StringBuilder();   
  125.   
  126.      if (string.IsNullOrEmpty(keyValue))   
  127.      {   
  128.           return strSQL;   
  129.      }   
  130.   
  131.      Type t = obj.GetType();//獲得該類的Type   
  132.   
  133.      strSQL.Append("update " + tableName + " set ");   
  134.   
  135.      string subSQL = "";   
  136.   
  137.      string condition = " where " + tableKey + "='" + keyValue.Replace("'""''") + "'";   
  138.   
  139.   
  140.      //再用Type.GetProperties獲得PropertyInfo[]   
  141.      foreach (PropertyInfo pi in t.GetProperties())   
  142.      {   
  143.   
  144.           object name = pi.Name;//用pi.GetValue獲得值   
  145.   
  146.           // 替換Sql注入符   
  147.           string value1 = Convert.ToString(pi.GetValue(obj, null)).Replace("'""''");   
  148.   
  149.           //string dataType = pi.PropertyType.ToString().ToLower();   
  150.   
  151.           string properName = name.ToString().ToLower();   
  152.   
  153.           if (!string.IsNullOrEmpty(value1) && properName != tableKey.ToLower() && properName != BaseSet.PrimaryKey.ToLower() && properName != BaseSet.TableName.ToLower() && value1 != BaseSet.DateTimeLongNull && value1 != BaseSet.DateTimeShortNull)   
  154.           {   
  155.                // 判斷是否爲空   
  156.                if (value1 == BaseSet.NULL)   
  157.                {   
  158.                    value1 = "";   
  159.                }   
  160.   
  161.                subSQL += Convert.ToString(name) + "='" + value1 + "',";   
  162.   
  163.           }   
  164.   
  165.      }   
  166.   
  167.      // 去掉最後一個,   
  168.      subSQL = subSQL.TrimEnd(',');   
  169.   
  170.      // 拼接上更新子句   
  171.      strSQL.Append(subSQL);   
  172.   
  173.      // 加入更新條件   
  174.      strSQL.Append(condition);   
  175.   
  176.      return strSQL;   
  177.   
  178. }   
  179.   
  180. public class BaseSet   
  181. {   
  182.     public static string NULL   
  183.     {   
  184.          get { return "@null"; }   
  185.   
  186.     }   
  187.   
  188.     public static string DateTimeShortNull   
  189.     {   
  190.          get { return "0001-1-1 0:00:00"; }   
  191.   
  192.     }   
  193.   
  194.     public static string DateTimeLongNull   
  195.     {   
  196.          get { return "0001-01-01 00:00:00"; }   
  197.   
  198.     }   
  199.   
  200.     public static string PrimaryKey   
  201.     {   
  202.          get { return "PrimaryKey"; }   
  203.   
  204.     }   
  205.   
  206.     public static string TableName   
  207.     {   
  208.          get { return "TableName"; }   
  209.   
  210.     }   
  211. }  
  212.  
  213. #region 實體樣例   
  214. [Serializable]   
  215. public class SortsInfo   
  216. {   
  217.      private int _SortID;   
  218.      private string _SortName;   
  219.      public string TableName   
  220.      {   
  221.          get { return "Sorts"; }   
  222.      }   
  223.      public string PrimaryKey   
  224.      {   
  225.          get { return "SortID"; }   
  226.      }   
  227.      public int SortID   
  228.      {   
  229.          get { return _SortID; }   
  230.          set  
  231.          {   
  232.              _SortID = value;   
  233.          }   
  234.      }   
  235.      public string SortName   
  236.      {   
  237.          get { return _SortName; }   
  238.          set  
  239.          {   
  240.              _SortName = value;   
  241.          }   
  242.      }   
  243.   
  244. }  
  245.  
  246. #endregion  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章