使用 MySQL 搜索:如何转义通配符
我目前正在使用如下查询(使用 JDBC)搜索我的数据库:
"... AND LCASE(Items.Name) LIKE '%" + searchString.toLowerCase() + "%';"
现在,这显然非常糟糕,因为它允许 SQL 注入以及插入通配符,例如 % 和 _。
我的问题是,如何进行查询,即使 searchString 包含任何这些字符,它们也会按字面意思处理?
I am currently searching my database with a query (using JDBC) like this:
"... AND LCASE(Items.Name) LIKE '%" + searchString.toLowerCase() + "%';"
Now, this is obviously very bad, because it allows for SQL injection as well as insertion of wildcard symbols such as % and _.
My question is, how can I do a query such that even if the searchString contains any of these characters, they will be treated literally?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,不要将
LCASE
与LIKE
一起使用,除非您使用区分大小写的语言环境(这不是 MySQL 的默认设置)。至于转义这些字符,只需在它们前面加上
\
字符即可,这样foo%bar
就变成了foo\%bar
。(自从我使用 Java 以来已经有一段时间了,但这可能有效:)
(或使用正则表达式):
就防止 SQL 注入而言,只需照常绑定变量即可:
并创建绑定字符串,如下所示:
First, don't use
LCASE
withLIKE
unless you're using a case-sensitive locale (which is not the default with MySQL).As far as escaping those characters, just prefix them with a
\
character, sofoo%bar
becomesfoo\%bar
.(It's been a while since I've used Java, but might this work:)
(or using a regex):
As far as preventing SQL injection, just bind the variable as normal:
And create the bound string like:
根据这个,你可以逃脱使用斜杠 (
\
) 或指定您自己的转义字符:您必须在您的语言 (Java) 中搜索并替换 mysql
LIKE
通配符?)、%
和_
分别替换为\%
和\_
。您上面提到的其他模式匹配不受支持(根据链接的文档)。According to this, you can escape them using a slash (
\
) or by specifying your own escape character:You'll have to do a search and replace on the mysql
LIKE
wildcard symbols in your language (Java?),%
and_
to replace them with\%
and\_
respectively. The other pattern matches you mention above are not (according to the linked docs) supported.