Store string with special characters like quotes or backslash in postgresql table

postgresql, sql

Solution

As per the SQL standard, quotes are delimited by doubling them, ie:

insert into table (column) values ('I''m OK')

If you replace every single quote in your text with two single quotes, it will work.

Normally, a backslash escapes the following character, but literal backslashes are similarly escaped by using two backslashes"

insert into table (column) values ('Look in C:\\Temp')

Problem

I have a string with value `'MAX DATE QUERY: SELECT iso_timestamp(MAX(time_stamp)) AS MAXTIME FROM observation WHERE offering_id = 'HOBART''` But on inserting into postgresql table i am getting error: org.postgresql.util.PSQLException: ERROR: syntax error at or near "HOBART". This is probably because my string contains single quotes. I don't know my string value. Every time it keeps changing and may contain special characters like \ or something since I am reading from a file and saving into postgres database. Please give a general solution to escape such characters.

Original source

Related problems