C# constructing parameter query SQL - LIKE %

随声附和 提交于 2019-11-26 09:58:31

问题


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

Here is what I am trying to acheive (please note that the database is 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.

Suggestions are welcome!


回答1:


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:


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



回答3:


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:

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


来源:https://stackoverflow.com/questions/664314/c-sharp-constructing-parameter-query-sql-like

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!