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


This was my solution:

SQL1 = 'SELECT * FROM %s' %table_name
SQL2 = SQL1+' WHERE created_on < date (%s);'
cursor.execute(SQL2, (time_from, ))

      



Table names cannot be passed in the usual way as they are converted to an object in the SQL command

0


source


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







All Articles