Psycopg2 cursor.execute () pass names and elements of variable table
I was trying to get a specific group of objects from a specific table in postgres database using psycopg2. all the advice I've seen when passing variables to cursor.execute (SQL) doesn't seem to work with the two types of variables
this is what I got tired of first, what didn't work:
SQL = 'SELECT * FROM %s WHERE created_on < date (%s);'
cursor.execute(SQL,[(table_name), (time_from)])
this always returned syntax error where table_name was inserted
+3
source to share
2 answers
As mentioned in Antoine's comment, the documentation now suggests this method for composing table names.
from psycopg2 import sql
cur.execute(
sql.SQL("insert into {} values (%s, %s)")
.format(sql.Identifier('my_table')),
[10, 20])
+1
source to share