[英]psycopg2 interpolate table name in executemany statement
I am trying to insert data into a table. 我试图将数据插入表中。 The table is determined in the beging of the program and remains constant throughout.
该表在程序的结构中确定,并始终保持不变。 How do I interpolate the table name in an execute many statement like the one below?
如何在执行多语句中插入表名,如下所示?
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)
As stated in the official documentation: "Only query values should be bound via this method: it shouldn't be used to merge table or field names to the query. If you need to generate dynamically an SQL query (for instance choosing dynamically a table name) you can use the facilities provided by the psycopg2.sql module." 正如官方文档中所述:“只有查询值才能通过此方法绑定:它不应该用于将表或字段名称合并到查询中。如果需要动态生成SQL查询(例如动态选择表格) name)你可以使用psycopg2.sql模块提供的工具。“
It has the following syntax: 它具有以下语法:
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)
More on http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql 更多信息,请访问http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.