Holey_yan

[C#] SqlModule

Jul 4th, 2016
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 17.64 KB | None | 0 0
  1. /**************************************************/
  2. /* Date   : 2017/03/02                            */
  3. /* E-mail : [email protected]                   */
  4. /* Note   :                                       */
  5. /*    char     -> String                          */
  6. /*    nchar    -> String                          */
  7. /*    decimal  -> decimal                         */
  8. /*    date     -> DateTime                        */
  9. /*    datetime -> DateTime                        */
  10. /*    time     -> TimeSpan                        */
  11. /**************************************************/
  12.  
  13. using System;
  14. using System.Collections.Generic;
  15. using System.Data.SqlClient;
  16. using System.Reflection;
  17.  
  18. namespace YanLib.SqlModule
  19. {
  20.     public class SqlModule<T> where T : new()
  21.     {
  22.         /// <summary>
  23.         /// 搜尋
  24.         /// </summary>
  25.         /// <param name="SqlServer">主機位址</param>
  26.         /// <param name="SqlName">主機名稱</param>
  27.         /// <param name="SqlUid">登入帳號</param>
  28.         /// <param name="SqlPwd">登入密碼</param>
  29.         /// <param name="TableName">資料表名稱</param>
  30.         /// <param name="Where">條件約束語句,預設為空(搜尋所有)</param>
  31.         /// <param name="OrderBy">資料排序,預設為空(不排序)</param>
  32.         /// <param name="Timeout">連線超時時間,單位為秒(s),預設為 10 秒</param>
  33.         /// <param name="Trusted_Connection">信任連接,預設為 True</param>
  34.         /// <returns>回傳 List<T>,若搜尋過程中發生 Exception 則傳回 null</returns>
  35.         public static List<T> SqlSearch(string SqlServer, string SqlName, string SqlUid, string SqlPwd, string TableName,
  36.                                         string Where = null, List<OrderByPair> OrderBy = null, int Timeout = 10, bool Trusted_Connection = true)
  37.         {
  38.             // A Result of Dictionary
  39.             List<T> respT = new List<T>();
  40.  
  41.             // Create a Connection object
  42.             using (SqlConnection connection = new SqlConnection(string.Format("Data Source={0}; Database={1}; User ID={2}; Password={3}; Connection Timeout={4}; Trusted_Connection={5};",
  43.                                                                               SqlServer, SqlName, SqlUid, SqlPwd, Timeout.ToString(), Trusted_Connection.ToString())))
  44.             {
  45.                 try
  46.                 {
  47.                     // Open the connection
  48.                     connection.Open();
  49.                 }
  50.                 catch (SqlException)
  51.                 {
  52.                     return null;
  53.                 }
  54.  
  55.                 try
  56.                 {
  57.                     // Set ORDER BY value
  58.                     string orderBy = string.Empty;
  59.                     if (OrderBy != null)
  60.                     {
  61.                         foreach (OrderByPair orderCondition in OrderBy)
  62.                         {
  63.                             orderBy += string.Format("{0} {1},", orderCondition.GetKey(), orderCondition.GetModeStr());
  64.                         }
  65.                         orderBy = orderBy.Trim(',');
  66.                     }
  67.                     // Create a Command object
  68.                     SqlCommand myCmd = new SqlCommand(string.Format("SELECT * FROM {0}", TableName) +
  69.                                                       (string.IsNullOrWhiteSpace(Where) ? "" : string.Format(" WHERE {0}", Where)) +
  70.                                                       (OrderBy == null ? ";" : string.Format(" ORDER BY {0};", orderBy)), connection);
  71.                     // Concatenate the query result into a string
  72.                     SqlDataReader myReader = myCmd.ExecuteReader();
  73.  
  74.                     while (myReader.Read())
  75.                     {
  76.                         T getItem = new T();
  77.                         foreach (FieldInfo field in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance))
  78.                         {
  79.                             for (int i = 0; i < myReader.FieldCount; i++)
  80.                             {
  81.                                 if (string.Equals(myReader.GetName(i), field.Name))
  82.                                 {
  83.                                     try
  84.                                     {
  85.                                         if (myReader.GetDataTypeName(i).Equals("int"))
  86.                                         {
  87.                                             field.SetValue(getItem, myReader.GetInt32(i));
  88.                                         }
  89.                                         else if (myReader.GetDataTypeName(i).Equals("float"))
  90.                                         {
  91.                                             field.SetValue(getItem, myReader.GetFloat(i));
  92.                                         }
  93.                                         else if (myReader.GetDataTypeName(i).Equals("decimal"))
  94.                                         {
  95.                                             field.SetValue(getItem, myReader.GetDecimal(i));
  96.                                         }
  97.                                         else if (myReader.GetDataTypeName(i).Contains("char"))
  98.                                         {
  99.                                             field.SetValue(getItem, myReader.GetString(i).Trim(' '));
  100.                                         }
  101.                                         else if (myReader.GetDataTypeName(i).Equals("date") || myReader.GetDataTypeName(i).Equals("datetime"))
  102.                                         {
  103.                                             field.SetValue(getItem, myReader.GetDateTime(i));
  104.                                         }
  105.                                         else if (myReader.GetDataTypeName(i).Equals("time"))
  106.                                         {
  107.                                             field.SetValue(getItem, myReader.GetTimeSpan(i));
  108.                                         }
  109.                                     }
  110.                                     catch (System.Data.SqlTypes.SqlNullValueException)
  111.                                     {
  112.                                         field.SetValue(getItem, null);
  113.                                     }
  114.                                     break;
  115.                                 }
  116.                             }
  117.                         }
  118.                         respT.Add(getItem);
  119.                     }
  120.                 }
  121.                 catch (SqlException)
  122.                 {
  123.                     return null;
  124.                 }
  125.             }
  126.             return (respT);
  127.         }
  128.  
  129.         /// <summary>
  130.         /// 插入
  131.         /// </summary>
  132.         /// <param name="SqlServer">主機位址</param>
  133.         /// <param name="SqlName">主機名稱</param>
  134.         /// <param name="SqlUid">登入帳號</param>
  135.         /// <param name="SqlPwd">登入密碼</param>
  136.         /// <param name="TableName">資料表名稱</param>
  137.         /// <param name="InsertItem">欲插入之資料</param>
  138.         /// <param name="Timeout">連線超時時間,單位為秒(s),預設為 10 秒</param>
  139.         /// <param name="Trusted_Connection">信任連接,預設為 True</param>
  140.         /// <returns>傳回長度為 2 之字串陣列,[0] 表示插入結果,[1] 表示受影響之資料數或錯誤訊息</returns>
  141.         public static string[] SqlInsert(string SqlServer, string SqlName, string SqlUid, string SqlPwd, string TableName, T InsertItem, int Timeout = 10, bool Trusted_Connection = true)
  142.         {
  143.             // Create a Connection object
  144.            
  145.             using (SqlConnection connection = new SqlConnection(string.Format("Data Source={0}; Database={1}; User ID={2}; Password={3}; Connection Timeout={4}; Trusted_Connection={5};",
  146.                                                                               SqlServer, SqlName, SqlUid, SqlPwd, Timeout.ToString(), Trusted_Connection.ToString())))
  147.             {
  148.                 try
  149.                 {
  150.                     // Open the connection
  151.                     connection.Open();
  152.                 }
  153.                 catch (SqlException ex)
  154.                 {
  155.                     return (new string[] { "false", ex.Message });
  156.                 }
  157.  
  158.                 // Do work here; connection closed on following line.
  159.                 try
  160.                 {
  161.                     string[] Params = new string[] { string.Empty, string.Empty };
  162.                     foreach (FieldInfo field in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance))
  163.                     {
  164.                         try
  165.                         {
  166.                             Params[0] += string.Format("[{0}],", field.Name);
  167.                             if (field.GetValue(InsertItem).GetType() == typeof(char))
  168.                             {
  169.                                 Params[1] += string.Format("'{0}'", field.GetValue(InsertItem));
  170.                             }
  171.                             else if (field.GetValue(InsertItem).GetType() == typeof(string))
  172.                             {
  173.                                 Params[1] += string.Format("'{0}'", field.GetValue(InsertItem));
  174.                             }
  175.                             else if (field.GetValue(InsertItem).GetType() == typeof(DateTime))
  176.                             {
  177.                                 Params[1] += string.Format("'{0}'", ((DateTime)(field.GetValue(InsertItem))).ToString("yyyy-MM-dd HH:mm:ss"));
  178.                             }
  179.                             else if (field.GetValue(InsertItem).GetType() == typeof(TimeSpan))
  180.                             {
  181.                                 Params[1] += string.Format("'{0}'", field.GetValue(InsertItem).ToString());
  182.                             }
  183.                             else
  184.                             {
  185.                                 Params[1] += field.GetValue(InsertItem);
  186.                             }
  187.                             Params[1] += ',';
  188.                         }
  189.                         catch (NullReferenceException)
  190.                         {
  191.                             Params[1] += "null";
  192.                         }
  193.                     }
  194.                     Params[0] = Params[0].TrimEnd(','); Params[1] = Params[1].TrimEnd(',');
  195.                     SqlCommand command = new SqlCommand(string.Format("INSERT INTO {0} ({1}) VALUES ({2});", TableName, Params[0], Params[1]), connection);
  196.                     return (new string[] { "true", command.ExecuteNonQuery().ToString() });
  197.                 }
  198.                 catch (SqlException ex)
  199.                 {
  200.                     return (new string[] { "false", ex.Message });
  201.                 }
  202.             }
  203.         }
  204.  
  205.         /// <summary>
  206.         /// 更新
  207.         /// </summary>
  208.         /// <param name="SqlServer">主機位址</param>
  209.         /// <param name="SqlName">主機名稱</param>
  210.         /// <param name="SqlUid">登入帳號</param>
  211.         /// <param name="SqlPwd">登入密碼</param>
  212.         /// <param name="TableName">資料表名稱</param>
  213.         /// <param name="UpdateItem">欲更新之資料</param>
  214.         /// <param name="Where">條件約束語句</param>
  215.         /// <param name="Timeout">連線超時時間,單位為秒(s),預設為 10 秒</param>
  216.         /// <param name="Trusted_Connection">信任連接,預設為 True</param>
  217.         /// <returns>傳回長度為 2 之字串陣列,[0] 表示更新結果,[1] 表示受影響之資料數或錯誤訊息</returns>
  218.         public static string[] SqlUpdate(string SqlServer, string SqlName, string SqlUid, string SqlPwd, string TableName,
  219.                                          T UpdateItem, string Where, int Timeout = 10, bool Trusted_Connection = true)
  220.         {
  221.             // Create a Connection object
  222.             using (SqlConnection connection = new SqlConnection(string.Format("Data Source={0}; Database={1}; User ID={2}; Password={3}; Connection Timeout={4}; Trusted_Connection={5};",
  223.                                                                               SqlServer, SqlName, SqlUid, SqlPwd, Timeout.ToString(), Trusted_Connection.ToString())))
  224.             {
  225.                 try
  226.                 {
  227.                     // Open the connection
  228.                     connection.Open();
  229.                 }
  230.                 catch (SqlException ex)
  231.                 {
  232.                     return (new string[] { "false", ex.Message });
  233.                 }
  234.  
  235.                 // Do work here; connection closed on following line.
  236.                 try
  237.                 {
  238.                     // Set UPDATE value
  239.                     string Params = string.Empty;
  240.                     foreach (FieldInfo field in typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance))
  241.                     {
  242.                         try
  243.                         {
  244.                             if (field.GetValue(UpdateItem).GetType() == typeof(char))
  245.                             {
  246.                                 Params += string.Format("'{0}'", field.GetValue(UpdateItem));
  247.                             }
  248.                             else if (field.GetValue(UpdateItem).GetType() == typeof(string))
  249.                             {
  250.                                 Params += string.Format("{0}={1}", field.Name, string.Format("'{0}'", field.GetValue(UpdateItem)));
  251.                             }
  252.                             else if (field.GetValue(UpdateItem).GetType() == typeof(DateTime))
  253.                             {
  254.                                 Params += string.Format("{0}={1}", field.Name, string.Format("'{0}'", ((DateTime)(field.GetValue(UpdateItem))).ToString("yyyy-MM-dd HH:mm:ss")));
  255.                             }
  256.                             else if (field.GetValue(UpdateItem).GetType() == typeof(TimeSpan))
  257.                             {
  258.                                 Params += string.Format("{0}='{1}'", field.Name, field.GetValue(UpdateItem).ToString());
  259.                             }
  260.                             else
  261.                             {
  262.                                 Params += string.Format("{0}={1}", field.Name, field.GetValue(UpdateItem));
  263.                             }
  264.                         }
  265.                         catch (NullReferenceException)
  266.                         {
  267.                             Params += string.Format("{0}={1}", field.Name, "null");
  268.                         }
  269.                         Params += ',';
  270.                     }
  271.                     Params = Params.TrimEnd(',');
  272.  
  273.                     SqlCommand command = new SqlCommand(string.Format("UPDATE {0} SET {1} WHERE {2};", TableName, Params, Where), connection);
  274.                     return (new string[] { "true", command.ExecuteNonQuery().ToString() });
  275.                 }
  276.                 catch (SqlException ex)
  277.                 {
  278.                     return (new string[] { "false", ex.Message });
  279.                 }
  280.             }
  281.         }
  282.  
  283.         /// <summary>
  284.         /// 刪除
  285.         /// </summary>
  286.         /// <param name="SqlServer">主機位址</param>
  287.         /// <param name="SqlName">主機名稱</param>
  288.         /// <param name="SqlUid">登入帳號</param>
  289.         /// <param name="SqlPwd">登入密碼</param>
  290.         /// <param name="TableName">資料表名稱</param>
  291.         /// <param name="Where">條件約束語句</param>
  292.         /// <param name="Timeout">連線超時時間,單位為秒(s),預設為 10 秒</param>
  293.         /// <param name="Trusted_Connection">信任連接,預設為 True</param>
  294.         /// <returns>傳回長度為 2 之字串陣列,[0] 表示刪除結果,[1] 表示受影響之資料數或錯誤訊息</returns>
  295.         public static string[] SqlDelete(string SqlServer, string SqlName, string SqlUid, string SqlPwd, string TableName, string Where, int Timeout = 10, bool Trusted_Connection = true)
  296.         {// Create a Connection object
  297.             using (SqlConnection connection = new SqlConnection(string.Format("Data Source={0}; Database={1}; User ID={2}; Password={3}; Connection Timeout={4}; Trusted_Connection={5};",
  298.                                                                               SqlServer, SqlName, SqlUid, SqlPwd, Timeout.ToString(), Trusted_Connection.ToString())))
  299.             {
  300.                 try
  301.                 {
  302.                     // Open the connection
  303.                     connection.Open();
  304.                 }
  305.                 catch (SqlException ex)
  306.                 {
  307.                     return (new string[] { "false", ex.Message });
  308.                 }
  309.  
  310.                 // Do work here; connection closed on following line.
  311.                 try
  312.                 {
  313.                     SqlCommand command = new SqlCommand(string.Format("DELETE FROM {0} WHERE {1}", TableName, Where), connection);
  314.                     return (new string[] { "true", command.ExecuteNonQuery().ToString() });
  315.                 }
  316.                 catch (SqlException ex)
  317.                 {
  318.                     return (new string[] { "false", ex.Message });
  319.                 }
  320.             }
  321.         }
  322.     }
  323.  
  324.     public class OrderByPair
  325.     {
  326.         private string key = "";
  327.         private OrderMode mode = OrderMode.ASC;
  328.  
  329.         public OrderByPair(string key, OrderMode mode)
  330.         {
  331.             this.key = key;
  332.             this.mode = mode;
  333.         }
  334.  
  335.         public string GetKey()
  336.         {
  337.             return this.key;
  338.         }
  339.  
  340.         public void SetKey(string key)
  341.         {
  342.             this.key = key;
  343.         }
  344.  
  345.         public OrderMode GetMode()
  346.         {
  347.             return this.mode;
  348.         }
  349.  
  350.         public void SetMode(OrderMode mode)
  351.         {
  352.             this.mode = mode;
  353.         }
  354.  
  355.         public string GetModeStr()
  356.         {
  357.             return this.mode.ToString();
  358.         }
  359.     }
  360.  
  361.     public enum OrderMode
  362.     {
  363.         ASC,
  364.         DESC
  365.     }
  366. }
Advertisement
Add Comment
Please, Sign In to add comment