本文以一个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语句中是否包含有非法危险的字符:
////// 检测是否有Sql危险字符 /// /// 要判断字符串 ///判断结果 public static bool IsSafeSqlString(string str) { return !Regex.IsMatch(str, @"[-|;|,|/|(|)|[|]|}|{|%|@|*|!|']"); } ////// 改正sql语句中的转义字符 /// public static string mashSQL(string str) { string str2; if (str == null) { str2 = ""; } else { str = str.Replace("'", "'"); str2 = str; } return str2; }



