如何在带有参数的SQL查询中使用通配符

ova*_*ein 13 c# sql

假设我有一个基本查询,如下所示:

 SELECT holiday_name
 FROM holiday
 WHERE holiday_name LIKE %Hallow%
Run Code Online (Sandbox Code Playgroud)

这在我的SQL查询窗格中执行正常并返回'Halloween'.当我尝试在我的代码中使用带有通配符'%'字符的参数时,会出现问题.

SqlConnection Connection = null;
SqlCommand Command = null;

string ConnectionString = ConfigurationManager.ConnectionStrings["SQLdb"].ConnectionString;
string CommandText = "SELECT holiday_name "
                   + "FROM holiday "
                   + "WHERE holiday_name LIKE %@name%";
Connection = new SqlConnection(ConnectionString);

try
{
      Connection.Open();
      Command = new SqlCommand(CommandText, Connection);
      Command.Parameters.Add(new SqlParameter("name", HolidayTextBox.Text));
      var results = Command.ExecuteScalar();
}

catch (Exception ex)
{   
     //error stuff here       
}

finally
{
    Command.Dispose();
    Connection.Close();
}
Run Code Online (Sandbox Code Playgroud)

这会引发错误的语法错误.我已经尝试将'%'移动到我的参数中

Command.Parameters.Add(new SqlParameter("%name%", HolidayTextBox.Text));
Run Code Online (Sandbox Code Playgroud)

但后来我收到一条错误,说我没有声明标量变量'@name'.那么,如何正确格式化通配符以包含在查询参数中?任何帮助表示赞赏!

All*_*enG 23

首先,你的SqlParameter名字@name不是name.

其次,我会移动你的通配符.

所以它看起来像这样:

string CommandText = "SELECT holiday_name "
               + "FROM holiday "
               + "WHERE holiday_name LIKE @name;"
Connection = new SqlConnection(ConnectionString);

try
{
  var escapedForLike = HolidatyTextBox.Text; // see note below how to construct 
  string searchTerm = string.Format("%{0}%", escapedForLike);
  Connection.Open();
  Command = new SqlCommand(CommandText, Connection);
  Command.Parameters.Add(new SqlParameter("@name", searchTerm));
  var results = Command.ExecuteScalar();
}
Run Code Online (Sandbox Code Playgroud)

注意,LIKE在传递参数时需要特别小心,并且需要转义一些字符使用sql参数在SQL LIKE语句中转义特殊字符.


gor*_*rdy 7

无论你做什么都不这样做:

string CommandText = "SELECT holiday_name "
                   + "FROM holiday "
                   + "WHERE holiday_name LIKE '%'" + HolidayTextBox.Text + "'%'";
Run Code Online (Sandbox Code Playgroud)

因为这将打开你的SQL注入,而不是这样做:

Command.Parameters.Add(new SqlParameter("@name", "%" + HolidayTextBox.Text + "%"));
Run Code Online (Sandbox Code Playgroud)

您可能想了解Command.Parameters.AddWithValue,例如:

Command.Parameters.AddWithValue("@name", "%" + HolidayTextBox.Text + "%");
Run Code Online (Sandbox Code Playgroud)

  • 小Bobby表喜欢SQL注入! (5认同)
  • 我不推荐SQL注入。 (2认同)
  • @zerkms让用户提供输入所以`var ="%"`对于像'DELETE FROM users WHERE userName LIKE'%'+ @var +'%'`这样的东西仍然很危险......(的确需要相信所有人)用户输入"LIKE"太多了,尤其是在更新语句中,可能也值得:)) (2认同)