postgresql psycopg 2-使用带有execute_values的SQL对象

zvms9eto  于 2023-01-08  发布在  PostgreSQL
关注(0)|答案(2)|浏览(300)

我正在使用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"""

可以使用字符串格式将表名插入到查询中,但显然不应该这样做,即使是在枪口下。如何安全地将可变表名插入到查询中并使用execute_values?我找不到一种内置的方法将SQL对象转换为字符串。

vmdwslir

vmdwslir1#

execute_values(cur, sql, argslist, template=None, page_size=100)中的参数sql应该是一个字符串:
sql -要执行的查询。它必须包含单个%s占位符,该占位符将被VALUES列表替换。示例:插入到mytable(ID,f1,f2)值%s.
使用as_string(context)方法:

extras.execute_values(cursor, query.as_string(cursor), dataset)
connection.commit()
wqsoz72f

wqsoz72f2#

由于execute_values()期望sql语句是字符串,因此您可以简单地使用:

queryText = "INSERT INTO {table} (uid,value) VALUES %s".format(table=sql.Identifier(tableName)

相关问题