C#构造参数查询SQL - LIKE %
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/664314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# constructing parameter query SQL - LIKE %
提问by
I am trying to build SQL for a parameter query in C# for a query which will contain the LIKE %%
command.
我正在尝试为 C# 中的参数查询构建 SQL,以获取包含LIKE %%
命令的查询。
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" + "%'");
将
%
字符添加到参数中,cmd.Parameters.AddWithValue(NAME, "%" + "JOHN" + "%");
或者
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!
欢迎提出建议!
采纳答案by Guffa
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" + "%");
回答by Chris
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("'","?"));
回答by Joel Coehoorn
var SQL = string.Format("SELECT * FROM {0} WHERE {1} LIKE '%' + ? + '%'", TABLE, NAME);
Cmd.CommandText = SQL;
Cmd.Parameters.Add("?", SqlDbType.VarChar, 50).Value = "JOHN";