Java replace 'c \

I work with mySQL. It cannot handle if ' is in the row that is added to the database.

I tried:

 replaceAll("'","\\'") 

and

 replaceAll("'","\'") 

Any ideas how I would like to replace ' with \' ?

+4
source share
2 answers

You need to avoid a double slash once for the string engine and once for the regular expression engine:

 replaceAll("'","\\\\'") 

Caution:. While this answers the question of how to insert a backslash in a string, of course, it should not be used to try to suppress SQL injection attacks.

To clarify: Imagine someone sending a line where the apostrophe has already escaped. This regular expression will cause the apostrophe to not be hidden (because now the backslash will disappear). So you need this regular expression to escape the apostrophe only if it is preceded by an even number of backslashes. It means

 replaceAll("(?<!\\\\)((?:\\\\\\\\)*)'", "$1\\\\'") 

It quickly becomes as inconspicuous as it seems, and it still does not apply to all cases.

+8
source

Do not use String to replace. Instead, use a prepared statement and thus let the JDBC driver remove the parameters for you:

 String sql = "select a.foo from a where a.bar = ?"; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, aStringWhichMightContainQuotes); ResultSet rs = stmt.executeQuery(); 

This is the right way to have database independent, reliable code that is not vulnerable to SQL injection attacks. And it also makes it more efficient if you execute the same query multiple times with different parameters.

See the JDBC tutorial for more information.

+18
source

Source: https://habr.com/ru/post/1400816/


All Articles