How do I add quotation marks/Apostrophe's to column value in psycopg2?

490 views Asked by At
information = "Hope they're well"     
cursor.execute("UPDATE table_name SET information='%s';" % information)

When adding this it will obviously produce and error as the execution will only try adding 'Hope they' and then the rest of the string will mess it up.

Obviously in php there is the option of making prepared statements so how do you do that in psycopg2?

I read this but didn't quite understand it and whether it was what I wanted to do.

1

There are 1 answers

0
That1Guy On BEST ANSWER

Don't format the string, simply pass your values as a second argument:

cursor.execute("UPDATE mytable SET col1 = %s, col2 = %s;", [arg1, arg2])

Optionally, use named arguments and pass a dictionary:

cursor.execute("""
    UPDATE mytable
    SET col1 = %(arg1)s, col2 = %(arg2)s
""",{'arg1':arg1, 'arg2':arg2})

psycopg2 will take care of everything else.

See here for more information.