How to use wildcards in SQL query with parameters

后端 未结 3 370
半阙折子戏
半阙折子戏 2020-12-06 16:47

Say I have a basic query, something like this:

 SELECT holiday_name
 FROM holiday
 WHERE holiday_name LIKE %Hallow%

This executes fine in m

3条回答
  •  死守一世寂寞
    2020-12-06 17:43

    First off, your SqlParameter name is @name not name.

    Second, I would move your wildcards.

    So it would look like this:

    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();
    }
    

    Note that LIKE requires special care when passing parameters and you need to escape some characters Escaping special characters in a SQL LIKE statement using sql parameters.

提交回复
热议问题