python - psycopg2 - 使用带有 execute_values 的 SQL 对象

标签 python sql database postgresql psycopg2

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

相关文章:

python - 是否可以使用openpyxl更改列宽?

Python 子进程 : how to retrieve the standard output

Python Pandas : equivalent to SQL's aggregate functions?

mysql - 查找mysql中每个 `key'列具有第二大日期的每条记录?

sql - 错误: ORDER BY items must appear in the select list if SELECT DISTINCT is specified

javascript - 无法存储非数字字符

sql - 如何将这些列转换/转置为 SQL 中的行?

python - 金融传染(疫情蔓延)模型遇到问题

c# - 如何在不使用命令生成器的情况下将行从我的数据集插入到我的数据库中?

Python,matplotlib pyplot show()不阻塞