복붙노트

[SQL] 매개 변수를 사용하여 SQL 쿼리에서 와일드 카드를 사용하는 방법

SQL

매개 변수를 사용하여 SQL 쿼리에서 와일드 카드를 사용하는 방법

나는이 같은 기본적인 쿼리, 뭔가를 말 :

 SELECT holiday_name
 FROM holiday
 WHERE holiday_name LIKE %Hallow%

내 SQL 쿼리 창 반환 '할로윈'에서이 실행하는 벌금. 내 코드에서 와일드 카드 '%'문자와 매개 변수를 사용하려고하면 내 문제가 발생합니다.

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

이것은 잘못된 구문 오류가 발생합니다. 나는 그렇게처럼 내 매개 변수에 '%'를 이동하려고했습니다

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

그러나 나는 스칼라 변수 '@name'를 선언하지 않은 말하는 오류가 발생합니다. 그래서, 당신은 어떻게 제대로 쿼리 매개 변수에 포함 할 와일드 카드 문자를 포맷합니까? 어떤 도움에 감사드립니다!

해결법

  1. ==============================

    1.첫째, 당신의 SqlParameter에 이름이 @name은 이름이 아닙니다.

    첫째, 당신의 SqlParameter에 이름이 @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();
    }
    

    매개 변수를 전달하고 SQL 매개 변수를 사용하여 SQL LIKE 문에 특수 문자를 이스케이프 일부 문자를 이스케이프해야 할 때 참고 LIKE는 특별한주의가 필요하다는.

  2. ==============================

    2.당신은이 작업을 수행하지 않습니다 무엇 :

    당신은이 작업을 수행하지 않습니다 무엇 :

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

    즉, SQL 주입을 열어하므로, 대신에이 작업을 수행 :

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

    당신은 Command.Parameters.AddWithValue, 예컨대에 대해 알고하실 수 있습니다 :

    Command.Parameters.AddWithValue("@name", "%" + HolidayTextBox.Text + "%");
    
  3. ==============================

    3.이 %의 검색 문자열이 아닌 쿼리의 일부가되어야합니다.

    이 %의 검색 문자열이 아닌 쿼리의 일부가되어야합니다.

    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));
    
  4. from https://stackoverflow.com/questions/19730941/how-to-use-wildcards-in-sql-query-with-parameters by cc-by-sa and MIT license