I have a JSONB object that I want to insert into my database that also contains single quote characters. The example below is just trimmed to highlight my issue:
[{"name": "Moody's Analytics BBB Corp Bd ETF"}]
I have tried just dumping that JSON object to a string and inserting it, but the single ' wont allow that to work and when I try to execute (where detail is the JSON object):
cur.execute("INSERT INTO schmea.table (id, detail) VALUES (?,?)", (sec_id, detail)
I get the following syntax error:
psycopg2.errors.SyntaxError: syntax error at or near ","
LINE 1: INSERT INTO schema.table (id, detail) VALUES (?,?)
^
All of the solutions I've found so far suggest turning the JSON object into a string using json.dumps() but that wont work in my situation because of the single ' character in the name.
Any help is appreciated here.
Edit: Was told that the proper bind is %s not ? but that changes the error to:
psycopg2.ProgrammingError: can't adapt type 'dict'
edit 2:
SOLUTION:
Using the correct %s binds and using json.dumps(detail) fixed the issue.
cur.execute("INSERT INTO schmea.table (id, detail) VALUES (%s,%s)", (sec_id, json.dumps(detail))
Thanks for your help!