构造参数查询SQL -类似%

时间:2020-12-24 16:41:32

I am trying to build SQL for a parameter query in C# for a query which will contain the LIKE %% command.

我正在尝试为c#中的一个参数查询构建SQL,该查询将包含类似%%的命令。

Here is what I am trying to acheive (please note that the database is Firebird)

这是我正在尝试的内容(请注意,该数据库是Firebird)

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE '%?%'", TABLE, NAME);
 cmd.Parameters.AddWithValue(NAME, "JOHN");

Now I have tried every single permutation to get the parameter to work, I have tried;

现在我尝试了每一个排列来让参数工作,我尝试了;

  • Adding the % character to the parameter,

    向参数添加%字符,

    cmd.Parameters.AddWithValue(NAME, "%" + "JOHN" + "%");
    
  • or

    cmd.Parameters.AddWithValue(NAME, "'%" + "JOHN" + "%'");
    

I cannot seem to get this to work, how can I use a parameter for the LIKE query to work.

我似乎无法让它工作,如何使用LIKE查询的参数来工作。

Suggestions are welcome!

建议欢迎!

3 个解决方案

#1


26  

You can't have parameters inside of a string literal in the query. Make the entire value the parameter, and add the wildcards to the string:

在查询中,字符串文本中不能有参数。将整个值作为参数,并将通配符添加到字符串中:

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE ?", TABLE, NAME);
Cmd.Parameters.AddWithValue(NAME, "%" + "JOHN" + "%");

#2


4  

var SQL = string.Format("SELECT * FROM {0} WHERE {1} LIKE '%' + ? + '%'", TABLE, NAME);
Cmd.CommandText = SQL;
Cmd.Parameters.Add("?", SqlDbType.VarChar, 50).Value = "JOHN";

#3


-5  

In the past when doing this, i've simply integrated it into the sql, making sure that i replace single quotes with question marks to deal with sql injection. Eg:

在过去,我只是将它集成到sql中,确保用问号替换单引号来处理sql注入。例如:

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE '%{2}%'",
  TABLE,
  NAME,
  JOHN.Replace("'","?"));

#1


26  

You can't have parameters inside of a string literal in the query. Make the entire value the parameter, and add the wildcards to the string:

在查询中,字符串文本中不能有参数。将整个值作为参数,并将通配符添加到字符串中:

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE ?", TABLE, NAME);
Cmd.Parameters.AddWithValue(NAME, "%" + "JOHN" + "%");

#2


4  

var SQL = string.Format("SELECT * FROM {0} WHERE {1} LIKE '%' + ? + '%'", TABLE, NAME);
Cmd.CommandText = SQL;
Cmd.Parameters.Add("?", SqlDbType.VarChar, 50).Value = "JOHN";

#3


-5  

In the past when doing this, i've simply integrated it into the sql, making sure that i replace single quotes with question marks to deal with sql injection. Eg:

在过去,我只是将它集成到sql中,确保用问号替换单引号来处理sql注入。例如:

var SQL = string.format("SELECT * FROM {0} WHERE {1} LIKE '%{2}%'",
  TABLE,
  NAME,
  JOHN.Replace("'","?"));