jueves, 7 junio 2007
Replacing Apostrophes from Strings // Cleaning String to pass them as SQL statements
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, preventing SQL injection. Many may say that using PreparedStatements is easier and safer, but in 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. In 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 postgreSQL 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.
String replacedString = "John's hand";
replacedString.replaceAll("'","\\\\'");
Technorati Tags: Pattern regex replaceAll String PreparedStatement apostrophe
Posted by at 8:25 AM in Java