如何使用用户输入和通配符编写 SQL 查询

发布于 2024-08-26 07:52:53 字数 318 浏览 4 评论 0原文

通常我将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

自找没趣 2024-09-02 07:52:53

如果您使用 准备好的语句(即 SQLiteCommand,DbCommand),我们将为您处理。例如:

using (SqlCommand myCommand = new SQLiteCommand("SELECT * FROM TABLE WHERE (COLUMN LIKE = '%' + @input + '%')"))
{
        myCommand.Parameters.AddWithValue("@input", input);
        // ...
}

另请参阅类似的上一个问题

If you use prepared statements (i.e. SQLiteCommand, a subclass of DbCommand), this will be taken care of for you. E.g.:

using (SqlCommand myCommand = new SQLiteCommand("SELECT * FROM TABLE WHERE (COLUMN LIKE = '%' + @input + '%')"))
{
        myCommand.Parameters.AddWithValue("@input", input);
        // ...
}

See also this similar previous question.

唯憾梦倾城 2024-09-02 07:52:53

RE:如何在单词或句子周围放置通配符,并禁止用户在单词之间放置通配符? (最好使 % 成为句子的一部分)

我认为您需要将用户提供的任何 % 替换为 \% 并使用

LIKE @Expression ESCAPE '\'

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

LIKE @Expression ESCAPE '\'
帅的被狗咬 2024-09-02 07:52:53

继续使用参数,但在绑定之前在参数中添加通配符。

C#:

  param = '%' + Regex.Replace(param, @"[%?]", String.Empty) + '%'

SQL:

select * from ... where key like :param

Continue using a param, but add the wildcard in the param prior to binding.

C#:

  param = '%' + Regex.Replace(param, @"[%?]", String.Empty) + '%'

SQL:

select * from ... where key like :param
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文