How to use wildcards in SQL query with parameters

后端 未结 3 368
半阙折子戏
半阙折子戏 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:29

    The %s should be part of the search string, not the query.

    string CommandText = "SELECT holiday_name "
                    + "FROM holiday "
                    + "WHERE holiday_name LIKE @name";
    Connection = new SqlConnection(ConnectionString);
    
    try
    {
        Connection.Open();
        Command = new SqlCommand(CommandText, Connection);
        string name = "%" + HolidayTextBox.Text + "%";
        Command.Parameters.Add(new SqlParameter("@name", name));
    
    0 讨论(0)
  • 2020-12-06 17:41

    whatever you do don't do this:

    string CommandText = "SELECT holiday_name "
                       + "FROM holiday "
                       + "WHERE holiday_name LIKE '%'" + HolidayTextBox.Text + "'%'";
    

    as that will open you up to sql injection, instead do this:

    Command.Parameters.Add(new SqlParameter("@name", "%" + HolidayTextBox.Text + "%"));
    

    you may like to know about Command.Parameters.AddWithValue, e.g:

    Command.Parameters.AddWithValue("@name", "%" + HolidayTextBox.Text + "%");
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题