SQL字符串過濾 檢測是否有危險(xiǎn)字符

字號(hào):


    一個(gè)C# SQL數(shù)據(jù)庫字串操作函數(shù),可實(shí)現(xiàn)對(duì)SQL字符串過濾、檢測SQL是否有危險(xiǎn)字符、修正sql語句中的轉(zhuǎn)義字符,確保SQL不被注入:
    SQL字符串過濾函數(shù):
    01public static bool ProcessSqlStr(string Str)
    02{
    03 bool ReturnValue = true;
    04 try
    05 {
    06 if (Str.Trim() != "")
    07 {
    08 string SqlStr ="exec|insert+|select+|delete|update|count|chr|mid|master+
    |truncate|char|declare|drop+|drop+table|creat+
    |create|*|iframe|script|";
    09 SqlStr +="exec+|insert|delete+|update+|count(|count+|chr+|+mid
    (|+mid+|+master+|truncate+|char+|
    +char(|declare+|drop+table|creat+table";
    10 string[] anySqlStr = SqlStr.Split('|');
    11 foreach (string ss in anySqlStr)
    12 {
    13 if (Str.ToLower().IndexOf(ss) >= 0)
    14 {
    15 ReturnValue = false;
    16 break;
    17 }
    18 }
    19 }
    20 }
    21 catch
    22 {
    23 ReturnValue = false;
    24 }
    25 return ReturnValue;
    26}
    以下是檢測SQL語句中是否包含有非法危險(xiǎn)的字符:
    view sourceprint?01///
    02/// 檢測是否有Sql危險(xiǎn)字符
    03///
    04/// 要判斷字符串
    05/// 判斷結(jié)果
    06public static bool IsSafeSqlString(string str)
    07{
    08 return !Regex.IsMatch(str, @"[-|;|,|/|(|)|[|]|}|{|%|@|*|!|']");
    09}
    10///
    11/// 改正sql語句中的轉(zhuǎn)義字符
    12///
    13public static string mashSQL(string str)
    14{
    15 string str2;
    16 if (str == null)
    17 {
    18 str2 = "";
    19 }
    20 else
    21 {
    22 str = str.Replace("'", "'");
    23 str2 = str;
    24 }
    25 return str2;
    26}