java 如何转义 SQL 查询中使用的特殊字符?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6530275/
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
How to escape special characters used in SQL query?
提问by Ankur
Is there a Java library for escaping special characters from a string that is going to be inserted into an SQL query.
是否有用于从要插入 SQL 查询的字符串中转义特殊字符的 Java 库。
I keep writing code to escape various things, but I keep finding some new issue trips me up. So a library that takes care of all or most of the possibilities would be very handy.
我一直在编写代码来逃避各种事情,但我不断发现一些新问题让我感到困惑。因此,处理所有或大部分可能性的库将非常方便。
EDIT: I am using MySQL (if that makes any difference).
编辑:我正在使用 MySQL(如果这有什么不同的话)。
回答by Maurice Perry
Well... jdbc. Pass the strings as parameters, and don't append them to the query string
嗯... jdbc。将字符串作为参数传递,不要将它们附加到查询字符串
回答by Ankur
A little bit more research points me to this:
多一点研究指出我这一点:
http://devwar.blogspot.com/2010/06/how-to-escape-special-characters-in.html
http://devwar.blogspot.com/2010/06/how-to-escape-special-characters-in.html
Which suggests to use apache.commons.lang.StringEscapeUtils
, I will try this out
建议使用apache.commons.lang.StringEscapeUtils
,我会试试这个
回答by Ryan Webb
I know this is a long time thread, but using the commonslang library there is a method called escapeSql(String)
. Also using prepared statement automatically escape the offending SQL character.
我知道这是一个很长的线程,但是使用 commonslang 库有一个名为escapeSql(String)
. 还使用准备好的语句自动转义有问题的 SQL 字符。