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
  • I have a similar issue, I am using hibernate queries and when trying to insert if a field contains single quotes, an exception is thrown Commented Jun 13, 2015 at 2:50

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

6 Comments

+1 for prepared statements. Those are really the proper way to do this.
+1 for prepared statements from me too. Be careful about exposing yourself to SQL injection attacks.
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.
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.
How do i go about solving similar issue when I am using hibernate saveOrUpdate(Object ), query and the issue occurs if one of the String fields in the Object contain a single quotes
|
2

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

Example:

SELECT * FROM users WHERE f_name='foo''bar';

Or you could use double dollar sign:

Example:

SELECT * FROM users WHERE f_name=$$foo''bar$$;

Both statements would search for the string foo'bar

4 Comments

Yes, this is a feature of standard SQL and PostgreSQL supports this. See postgresql.org/docs/current/static/…
But you still want to use bind variables and prepared statements.
I would agree that prepared statements are the way to go. But sometimes legacy code makes you choose your battles.
I doubt legacy code is an issue here. PostegreSQL has a JDBC driver.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.