場景
在winform中連接mysql數據庫並執行相應的sql,需要判斷sql字符串中是否指定的字符串比如
刪表的關鍵字drop database等,而且還得不區分大小寫,即包含大寫和小寫的都不被允許。
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
1、通過ToLower()將要比較的字符串全部轉換為小寫,然后進行比較
通過字符串的Contains方法判斷字符串中是否包含另一個字符串。
sql.ToLower().Contains(arr.ToLower())
2、完整示例方法
public static bool checkSql(string sql) { bool isRight = true; string[] notAllowKeyWords = { "drop", "drop database" , "drop table" , "truncate", "alter","rename" , "create" }; for (int i = 0; i < notAllowKeyWords.Length; i++) { string arr = notAllowKeyWords[i]; if (sql.ToLower().Contains(arr.ToLower())) { isRight = false; } } return isRight; }