syntax error at or near "I" while trying to insert rows in postgresql via python script

Viewed 393

Trying to insert a query into a postgres table via python code.

Code line:

query = f"INSERT INTO Phone (data, result, reason) VALUES ('{json.dumps(data)}', {val}, '{json.dumps(reason)}') RETURNING id;"

here, data and reason are columns of type json and result is a boolcolumn.

Query on printing the variable:

INSERT INTO Phone (data, result, reason) VALUES ('{'ICl': False, 'Poster': True, 'Lock': True, 'Model': 'ABC'}', True, '{}') RETURNING id;

Error:

syntax error at or near "I"
LINE 1: I
        ^

The same query on copy pasting into Table plus directly gives me no error and the row gets inserted.

Where is the error? Can't seem to understand why the query is giving me such error that too only in Python code. Please help.

1 Answers

You need to let psycopg2 handle the quoting for you.
Please try this:

query = """INSERT INTO Phone (data, result, reason) 
               VALUES (%s,%s,%s) RETURNING id;"""

cursor.execute(query, (json.dumps(data), val, json.dumps(reason),))
Related