我正在使用 execute_values 插入数据,它接受一个 sql 查询。查询是按照文档中的建议使用 psycopg2.sql.SQL 构造的,但 execute_values 不会采用该对象。
这是我的代码:
import psycopg2 as pg
from psycopg2 import extras
from psycopg2 import sql
config = {
'host' : 'localhost',
'user' : 'username',
'password' : 'password',
'dbname' : 'myDatabase'
}
connection = pg.connect(**config)
cursor = connection.cursor()
tableName = 'myTable'
dataset = [[1,2],[3,4],[5,6]]
queryText = "INSERT INTO {table} (uid,value) VALUES %s"
query = sql.SQL(queryText).format(table=sql.Identifier(tableName))
extras.execute_values(cursor,query,dataset)
最后一行报错如下:
AttributeError: 'Composed' object has no attribute 'encode'
如果查询直接指定为字符串,如下所示,则执行运行。
query = """INSERT INTO "myTable" (uid,value) VALUES %s"""
可以使用字符串格式将表名插入到查询中,但显然 shouldn't be done, even at gunpoint .如何安全地将变量表名插入查询并使用 execute_values?我找不到将 SQL 对象转换为字符串的内置方法。
最佳答案
execute_values(cur, sql, argslist, template=None, page_size=100)
中的参数sql
应该是一个字符串:
sql – the query to execute. It must contain a single %s placeholder, which will be replaced by a VALUES list. Example: "INSERT INTO mytable (id, f1, f2) VALUES %s".
使用 as_string(context)
方法:
extras.execute_values(cursor, query.as_string(cursor), dataset)
connection.commit()
关于python - psycopg2 - 使用带有 execute_values 的 SQL 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52341073/