Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 C# Split() 從 SQL 敘述中抽出操作欄位

前幾天工作上遇到一個需求:把 SQL 敘述裡被操作的欄位抽出來,掛到樹狀節點上顯示。這個判斷邏輯以後大概還會用到,於是整理成一篇筆記。目前版本尚未處理 Select * 的情況,只要補上判斷即可。

先認識 Split()

Split() 的作用是以指定字元切分字串,回傳一維字串陣列。它有六個重載:

String.Split 方法有 6 個重載函數:
1) public string[] Split(params char[] separator)        返回的字符串數組包含此實例中的子字符串
2) public string[] Split(char[] separator, int count)      返回的字符串數組包含此實例中的子字符串。 參數指定返回的子字符串的最大個數。
3) public string[] Split(char[] separator, StringSplitOptions options)      返回的字符串數組包含此字符串中的子字符串。 參數指定是否返回空數組元素。
4) public string[] Split(string[] separator, StringSplitOptions options)      返回的字符串數組包含此字符串中的子字符串。 參數指定是否返回空數組元素。
5) public string[] Split(char[] separator, int count, StringSplitOptions options)  返回的字符串數組包含此字符串中的子字符串(由指定 Unicode 字符數組的元素分隔)。 參數指定要返回子字符串的最大數量,以及是否返回空數組元素。
6) public string[] Split(string[] separator, int count, StringSplitOptions options)  返回的字符串數組包含此字符串中的子字符串(由指定字符串數組的元素分隔)。 參數指定要返回子字符串的最大數量,以及是否返回空數組元素。

其中 StringSplitOptions 是列舉型別,有兩個成員:None 表示結果保留空字串元素;RemoveEmptyEntries 表示把空字串元素濾掉。

整體思路就是:切分 → 逐項判斷 → 組出需要的欄位清單。

程式碼

        /// <summary>
        /// 獲取查詢字段代碼
        /// </summary>
        /// <param name="sOperationSQL"></param>
        /// <returns></returns>
        private string GetSQLOperateField(string sOperationSQL)
        {
            if (string.IsNullOrEmpty(sOperationSQL))
            {
                return string.Empty;
            }

            string sAppendNodeText = string.Empty;
            sOperationSQL = sOperationSQL.Trim();
            string[] strList = null;
            string sKey = sOperationSQL.Substring(0, 6);
            switch (sKey.ToUpper())
            {
                case "SELECT":
                {
                      strList = sOperationSQL.Split(new char[2] { ' ', ',' });
                      for (int i = 1; i < strList.Length; i++)
                      {
                            if (strList[i].ToUpper().Equals("FROM"))
                            {
                              break;
                            }

                            if (!string.IsNullOrEmpty(strList[i]))
                            {
                              sAppendNodeText += strList[i] + ",";
                            }
                      }

                      if (sAppendNodeText.Length > 1)
                      {
                        sAppendNodeText = sAppendNodeText.Substring(0, sAppendNodeText.Length - 1);
                      }
                      sAppendNodeText = "SELECT【" + sAppendNodeText + "】";
                      break;
                    }

                case "INSERT":
                {
                      strList = sOperationSQL.Trim().Split(new char[5] { ' ', ',', '(', ')', '\'' });
                      for (int i = 0; i < strList.Length; i++)
                      {
                            if (strList[i].ToUpper().Equals("WHERE"))
                            {
                              break;
                            }

                            if (!string.IsNullOrEmpty(strList[i]) && strList[i].IndexOf("=") > -1 && strList[i].Length > 1)
                            {
                              int iIndex = strList[i].IndexOf("=");
                              if (iIndex > 0)
                              {
                                sAppendNodeText += strList[i].Substring(0, iIndex) + ",";
                              }
                            }

                            if (!string.IsNullOrEmpty(strList[i]) && strList[i].IndexOf("=", 0, 1) > -1)
                            {
                            sAppendNodeText += strList[i - 1] + ",";
                            }

                            }

                      if (sAppendNodeText.Length > 1)
                      {
                        sAppendNodeText = sAppendNodeText.Substring(0, sAppendNodeText.Length - 1);
                      }

                      sAppendNodeText = "INSERT【" + sAppendNodeText + "】";
                      break;
                }

                case "UPDATE":
                {
                      strList = sOperationSQL.Trim().Split(new char[2] { ' ', ',' });
                      for (int i = 0; i < strList.Length; i++)
                      {
                            if (strList[i].ToUpper().Equals("WHERE"))
                            {
                              break;
                            }

                            if (!string.IsNullOrEmpty(strList[i]) && strList[i].IndexOf("=") > -1 && strList[i].Length > 1)
                            {
                              int iIndex = strList[i].IndexOf("=");
                              if (iIndex > 0)
                              {
                                sAppendNodeText += strList[i].Substring(0, iIndex) + ",";
                              }
                            }

                            if (!string.IsNullOrEmpty(strList[i]) && strList[i].IndexOf("=", 0, 1) > -1)
                            {
                            sAppendNodeText += strList[i - 1] + ",";
                            }

                            }

                      if (sAppendNodeText.Length > 1)
                      {
                        sAppendNodeText = sAppendNodeText.Substring(0, sAppendNodeText.Length - 1);
                      }

                      sAppendNodeText = "UPDATE【" + sAppendNodeText + "】";
                      break;
                }

                case "DELETE":
                {
                      strList = sOperationSQL.Trim().Split(new char[2] { ' ', ',' });
                      for (int i = 0; i < strList.Length; i++)
                      {
                            if (!string.IsNullOrEmpty(strList[i]) && strList[i].IndexOf("=") > -1 && strList[i].Length > 1)
                            {
                              int iIndex = strList[i].IndexOf("=");
                              if (iIndex > 0)
                              {
                                sAppendNodeText += strList[i].Substring(0, iIndex) + ",";
                              }
                            }

                            if (!string.IsNullOrEmpty(strList[i]) && strList[i].IndexOf("=", 0, 1) > -1)
                            {
                            sAppendNodeText += strList[i - 1] + ",";
                            }

                            }

                      if (sAppendNodeText.Length > 1)
                      {
                        sAppendNodeText = sAppendNodeText.Substring(0, sAppendNodeText.Length - 1);
                      }

                      sAppendNodeText = "DELETE【" + sAppendNodeText + "】";
                      break;
                }

            return sAppendNodeText;
        }

測試用例:

            string sSelSQL = "SELECT BSM FROM STUDENT";
            string sResult = GetSQLOperateField(sSelSQL);
            this.treeList1.AppendNode(new object[] { sResult }, null);
            string sUpdata = "UPDATE STUDENT SET NAME='JAMES'";
            sResult = GetSQLOperateField(sUpdata);
            this.treeList1.AppendNode(new object[] { sResult }, null);
            string sInsertSQL = "INSERT INTO STUDENT NAME='LUCY',ID='2001' WHERE SCORE='95'";
            sResult = GetSQLOperateField(sInsertSQL);
            this.treeList1.AppendNode(new object[] { sResult }, null);

需要留意的是,這種「靠切字元解析 SQL」的做法只適合結構單純的敘述;遇到巢狀查詢、函數呼叫或子字串裡含逗號的情況就會失準,正式環境仍建議用正規表達式或真正的 SQL 解析器。目前版本簡單但仍有精簡空間。

Copyright © Linux教程網 All Rights Reserved