Python psycopg2在executemany语句中插入表名

Python psycopg2在executemany语句中插入表名,python,psycopg2,Python,Psycopg2,我正在尝试将数据插入表中。表格在程序开始时确定,并始终保持不变。如何在下面的execute many语句中插入表名 tbl = 'table_name' rows = [{'this':x, 'that': x+1} for x in range(10)] cur.executemany("""INSERT INTO %(tbl)s VALUES( %(this)s,

我正在尝试将数据插入表中。表格在程序开始时确定,并始终保持不变。如何在下面的execute many语句中插入表名

tbl = 'table_name'
rows = [{'this':x, 'that': x+1} for x in range(10)]
cur.executemany("""INSERT INTO %(tbl)s 
                  VALUES(
                          %(this)s,
                          %(that)s
                  )""", rows)

正如官方文档中所述:“只能通过此方法绑定查询值:不应使用此方法将表名或字段名合并到查询中。如果需要动态生成SQL查询(例如,动态选择表名),可以使用psycopg2.SQL模块提供的功能。”

它具有以下语法:

from psycopg2 import sql
tbl = 'table_name'
rows = [{'this':x, 'that': x+1} for x in range(10)]
cur.execute(
    sql.SQL("INSERT INTO {} VALUES (%(this)s, %(that)s);"""")
        .format(sql.Identifier(tbl)), rows)

有关

的详细信息,因此无法插入表名: