【问题标题】:Update multiple postgresql records using unnest使用 unnest 更新多个 postgresql 记录
【发布时间】:2017-07-20 03:59:40
【问题描述】:

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

现在,我想批量更新记录,所以我一直在查看以下问题/答案:https://stackoverflow.com/a/33258295/596841https://stackoverflow.com/a/23324727/596841https://stackoverflow.com/a/39626473/596841,但我不确定如何使用@987654325 执行此操作@...

这是我用于更新的 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-16, 108264), (...)]

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

我得到的错误是:

psycopg2.ProgrammingError:返回“记录”的函数需要列定义列表 第 5 行:来自 unnest(ARRAY[(3.718244705238561e-16, 108264), (... ^

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

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

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

    【讨论】:

    • 啊啊啊!我曾尝试添加数据类型,但我不小心将它们放在变量之前...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2021-05-17
    相关资源
    最近更新 更多