使用unnes更新多个postgresql记录

2024-10-03 02:43:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据库表,有将近一百万条记录。 我添加了一个新列,名为concentration。 然后我有一个函数可以计算每个记录的“浓度”。在

现在,我想成批更新这些记录,所以我一直在研究以下问题/答案:https://stackoverflow.com/a/33258295/596841https://stackoverflow.com/a/23324727/596841和{a3},但我不确定如何使用unnest来完成这项工作。。。在

这是我的Python 3函数,用于执行更新:

def BatchUpdateWithConcentration(tablename, concentrations):
    connection = psycopg2.connect(dbname=database_name, host=host, port=port, user=username, password=password);
    cursor = connection.cursor();
    sql = """
    update #tablename# as t
    set
        t.concentration = s.con
        FROM unnest(%s) s(con, id)
        WHERE t.id = s.id;
    """
    cursor.execute(sql.replace('#tablename#',tablename.lower()), (concentrations,))
    connection.commit()
    cursor.close()
    connection.close()

concentrations是元组的数组:

[(3.718244705238561e-16108264),(…)]

第一个值是双精度值,第二个值是整数,分别表示浓度和rowid。在

我得到的错误是:

psycopg2.ProgrammingError: a column definition list is required for functions returning "record" LINE 5: FROM unnest(ARRAY[(3.718244705238561e-16, 108264), (... ^


Tags: 函数httpscomidhost记录connectionstackoverflow
1条回答
网友
1楼 · 发布于 2024-10-03 02:43:08

由于Psycopg将Python元组改编为Postgresql匿名记录,因此有必要指定数据类型:

from unnest(%s) s(con numeric, id integer)

相关问题 更多 >