SoFunction
Updated on 2025-03-06

SQL string filtering method for detecting whether there are dangerous characters in C#

This article takes a C# SQL database string operation function as an example to illustrate how to filter SQL strings, detect whether SQL is dangerous, correct escaped characters in SQL statements, and ensure that SQL is not injected. The specific implementation code is as follows:

SQL string filtering function:

public static bool ProcessSqlStr(string Str)
{
  bool ReturnValue = true;
  try
  {
    if (() != "")
    {
      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 = ('|');
      foreach (string ss in anySqlStr)
      {
        if (().IndexOf(ss) >= 0)
        {
          ReturnValue = false;
          break;
        }
      }
    }
  }
  catch
  {
    ReturnValue = false;
  }
  return ReturnValue;
}

The following are characters that detect whether SQL statements contain illegally dangerous characters:

/// <summary>
/// Detect whether there are dangerous Sql characters/// </summary>
/// <param name="str">To judge string</param>/// <returns>Judgement Results</returns>public static bool IsSafeSqlString(string str)
{
  return !(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']");
}
/// &lt;summary&gt;
/// Correct escape characters in sql statements/// &lt;/summary&gt;
public static string mashSQL(string str)
{
  string str2;
  if (str == null)
  {
    str2 = "";
  }
  else
  {
    str = ("\'", "'");
    str2 = str;
  }
  return str2;
}