psycopg2 cursor.execute()传入变量表名称和项目

Gra*_*oth 5 postgresql psycopg2 python-2.7

我试图使用psycopg2从Postgres数据库的特定表中获取一组对象。我在将变量传递给cursor.execute(SQL)命令时看到的所有建议似乎都不适用于两种类型的变量

这是我首先累的没用的:

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

这总是在插入table_name的地方返回语法错误

小智 4

正如 Antoine 的评论所提到的,文档现在建议使用这种方法来组成表名称。

from psycopg2 import sql

cur.execute(
sql.SQL("insert into {} values (%s, %s)")
    .format(sql.Identifier('my_table')),
[10, 20])
Run Code Online (Sandbox Code Playgroud)