如何转义SQL查询中使用的特殊字符?

时间:2022-05-22 22:29:01

Is there a Java library for escaping special characters from a string that is going to be inserted into an SQL query.

是否有一个Java库用于从将要插入到SQL查询的字符串中转义特殊字符。

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(如果有什么不同的话)。

3 个解决方案

#1


5  

Well... jdbc. Pass the strings as parameters, and don't append them to the query string

嗯…jdbc。将字符串作为参数传递,不要将它们附加到查询字符串

#2


2  

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.common。lang。stringescapeuls,我试试

#3


0  

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字符。

#1


5  

Well... jdbc. Pass the strings as parameters, and don't append them to the query string

嗯…jdbc。将字符串作为参数传递,不要将它们附加到查询字符串

#2


2  

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.common。lang。stringescapeuls,我试试

#3


0  

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字符。