gpt4 book ai didi

java - 如何从 SQL LIKE 子句中转义特殊字符?

转载 作者:行者123 更新时间:2023-12-01 17:45:44 25 4
gpt4 key购买 nike

我正在使用 https://www.baeldung.com/rest-api-search-language-rsql-fiql 上的指南来构建基于 RSQL 的 JPA 规范。

like 子句如下所示:

return builder.like(root.get(property), argument.toString().replace('*', '%'));

我的问题是,处理用户输入中转义特殊字符的最佳方法是什么?

例如,如果用户提供了字符串:

*my-search%-term*

上面的代码将其翻译为:

%my-search%-term%

我想转义字符串中的 % ,以便它不会被计算为 LIKE 子句中的 % 通配符。

以下帖子说明了每个数据库的 LIKE 特殊字符:

List of special characters for SQL LIKE clause

还要注意答案之一中的 comment:

It's impossible to write DBMS-independent code here, because you don't know what characters you're going to have to escape, and the standard says you can't escape things that don't need to be escaped. (See section 8.5/General Rules/3.a.ii.)

我想知道处理这个问题的最佳方法是什么?我在生产中使用 postgres,在测试中使用 h2,但理想情况下不希望解决方案与其中任何一个绑定(bind)。

最佳答案

为什么不使用正则表达式匹配而不是like

where col ~ <user input>

听起来您的用户可能更熟悉正则表达式。

如果您只想精确匹配而忽略所有通配符功能,则可以使用位置:

where position(<user input> in col) > 0

关于java - 如何从 SQL LIKE 子句中转义特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60868049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com