views:

1263

answers:

2

I'm inserting text from a Java application into a Postgresql database, but it all crashes when a ' char is encountered in the String. I've tried using replaceAll(" ' ", " \\' "); even diffrent variants of it with more \ chars, yet it still puts a single ' in the String without the escape sign.

Is there any way of replacing the ' with an \' in the String? Or another way of putting Strings containig single quotes into Postgresql?

+1  A: 

Most SQL implementations use '' (2 single quotes) to escape a single quote.

Example:

SELECT * FROM users WHERE f_name=''foobar'';
Matthew Vines
Yes, this is a feature of standard SQL and PostgreSQL supports this. See http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
Bill Karwin
But you still want to use bind variables and prepared statements.
Thilo
Thank you, that worked perfectly.
Malthan
I would agree that prepared statements are the way to go. But sometimes legacy code makes you choose your battles.
Matthew Vines
I doubt legacy code is an issue here. PostegreSQL has a JDBC driver.
Matthew Flaschen
+14  A: 

You shouldn't have to worry about doing this manually if you're using prepared statements properly.

Matthew Flaschen
+1 for prepared statements. Those are really the proper way to do this.
Joey
+1 for prepared statements from me too. Be careful about exposing yourself to SQL injection attacks.
Bert F
Thank you, I followed Your advice and changed it to a proper prepared statement, turned out I was using it the wrong way. This also resolved the issue.
Malthan
I'd recommend moving the accepted answer to this one. That way other folks will see the correct solution first. Nothing wrong, exactly, with the single quote escaping, but it's not generally a good practice to build SQL strings like that.
Kevin Day