Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2 cursor.execute() pass in variable table names and items

I was trying to get a certain group of objects from a specific table in a postgres database using psycopg2. all the advice I had seen on passing variables to a cursor.execute(SQL) command did not seem to work with two types of variables

this was what I tired first that didn't work:

SQL = 'SELECT * FROM %s WHERE created_on < date (%s);'
cursor.execute(SQL,[(table_name), (time_from)])

this always returned a syntax error where the table_name was inserted

like image 373
Graham Booth Avatar asked Oct 31 '22 22:10

Graham Booth


1 Answers

As mentioned by 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])
like image 77
jholland Avatar answered Nov 15 '22 05:11

jholland