如何使用用户输入和通配符编写 SQL 查询
通常我将 where 语句写为 WHERE key=@0
然后添加一个参数。现在我希望用户指定一些字母,例如“oat”,并希望在其周围添加与“coating”匹配的通配符%oat%
。那么我该如何编写查询,以便在用户输入(“搜索词”)周围使用通配符。
现在让我们更进一步。我不希望用户写%,这样他就不能做blah%ing。也许 % 是句子的一部分(或者它可能完全是非法的,但我更喜欢它是句子的一部分)。如何在单词或句子周围放置通配符并禁止用户在单词之间放置通配符? (最好将%作为句子的一部分)
C# ado.net sql/sqlite
Usually i write my where statements as WHERE key=@0
then add a param. Now i would like the user to specific a few letters such as 'oat' and would like to stick wildcards around it %oat%
which matches 'coating'. So how do i write the query so wildcards are around the user input (the 'seachword').
Now lets take it a step further. I would not like the user to write % so he cannot do blah%ing. Perhaps % is part of the sentence (or it could be flat out illegal but i prefer it be part of the sentence). How do i put my wildcards around a word or sentence and disallow the user from putting the wildcard between his words? (and preferably make % part of the sentence)
C# ado.net sql/sqlite
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用 准备好的语句(即 SQLiteCommand,DbCommand),我们将为您处理。例如:
另请参阅类似的上一个问题。
If you use prepared statements (i.e. SQLiteCommand, a subclass of DbCommand), this will be taken care of for you. E.g.:
See also this similar previous question.
RE:如何在单词或句子周围放置通配符,并禁止用户在单词之间放置通配符? (最好使 % 成为句子的一部分)
我认为您需要将用户提供的任何
%
替换为\%
并使用RE: How do i put my wildcards around a word or sentence and disallow the user from putting the wildcard between his words? (and preferably make % part of the sentence)
I think you would need to Replace any
%
the user supplies with\%
and use继续使用参数,但在绑定之前在参数中添加通配符。
C#:
SQL:
Continue using a param, but add the wildcard in the param prior to binding.
C#:
SQL: