psycopg2 在 executemany 语句中插入 table 名称
psycopg2 interpolate table name in executemany statement
我正在尝试将数据插入 table。 table 在程序开始时确定并始终保持不变。如何在如下所示的执行多个语句中插入 table 名称?
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)
如官方文档所述:"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."
语法如下:
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)
更多关于http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql
我正在尝试将数据插入 table。 table 在程序开始时确定并始终保持不变。如何在如下所示的执行多个语句中插入 table 名称?
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)
如官方文档所述:"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."
语法如下:
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)
更多关于http://initd.org/psycopg/docs/sql.html#module-psycopg2.sql