Replacing Apostrophes from Strings // Cleaning String to pass them as SQL statements
It is a very bad practice and unrecommended to send SQL statements directly to a database.
Such a simple thing as replacing an apostrophe with an escape character from a string sometimes can become a very tedious process, more if you're using String's replaceAll(...)
function.Replacing apostrophes from Strings may be very useful when creating Statements to pass to an SQL database, to prevent SQL injection. Using PreparedStatements is easier and safer, but on many occasions, you can't use prepared statements to accomplish what you need.
The problem with the replaceAll
function comes because of the arguments the function expects and which might be unclear for newbie developers. In the first place, you must pass a regular expression that suits what you want to replace. Secondly, the function expects another regular expression with the String's replacement. In some systems when passing apostrophes and other special characters as text, you must use the backslash as an escape character, just like in java. So if you want to insert "John's hand" as an argument to an Insert statement you must write something such as 'John\'s hand'.
If you refer to Pattern JavaDoc you can read:
The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.
Here is the answer to the problem. When replacing '
for \'
you need to place 4 backslashes before the apostrophe.
1String replacedString = "John's hand";
2replacedString.replaceAll("'","\\\\'");
Comments in "Replacing Apostrophes from Strings // Cleaning String to pass them as SQL statements"
For the specific case you mention, I think you would be better off using the '?' argument notation provided by JDBC PreparedStatements, rather than rolling your own. The Postgres driver should take care of it for you.
http://www.onjava.com/pub/a/onjava/excerpt/oraclejdbc_19/index.html?page=1
You can always add a utils function to avoid some boilerplate:
This way, you can call this function any time you need to pass an argument to an SQL statement.