本文以一個C#的SQL數據庫字串操作函數為例,說明如何實現對SQL字符串過濾、檢測SQL是否有危險字符、修正sql語句中的轉義字符,確保SQL不被注入等功能。具體實現代碼如下:
SQL字符串過濾函數:
public static bool ProcessSqlStr(string Str){ bool ReturnValue = true; try { if (Str.Trim() != "") { string SqlStr = "exec|insert+|select+|delete|update|count|chr|mid|master+|truncate|char|declare|drop+|drop+table|creat+|create|*|iframe|script|"; SqlStr += "exec+|insert|delete+|update+|count(|count+|chr+|+mid(|+mid+|+master+|truncate+|char+|+char(|declare+|drop+table|creat+table"; string[] anySqlStr = SqlStr.Split('|'); foreach (string ss in anySqlStr) { if (Str.ToLower().IndexOf(ss) >= 0) { ReturnValue = false; break; } } } } catch { ReturnValue = false; } return ReturnValue;}
以下是檢測SQL語句中是否包含有非法危險的字符:
/// <summary>/// 檢測是否有Sql危險字符/// </summary>/// <param name="str">要判斷字符串</param>/// <returns>判斷結果</returns>public static bool IsSafeSqlString(string str){ return !Regex.IsMatch(str, @"[-|;|,|//|/(|/)|/[|/]|/}|/{|%|@|/*|!|/']");}/// <summary>/// 改正sql語句中的轉義字符/// </summary>public static string mashSQL(string str){ string str2; if (str == null) { str2 = ""; } else { str = str.Replace("/'", "'"); str2 = str; } return str2;}
新聞熱點
疑難解答