从Python di批量更新PostgreSQL

2024-05-15 01:00:17 发布

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

在现有的PostgreSQL表中,我想用字典查找中的值来UPDATE几个现有列(见下面的dict)。有点像这里描述的nice blog post。但是,我不知道如何使用Python字典来实现这一点。可怕的伪代码来了:

d = {10:'chair', 11:'table', 12:'lamp', 
    20:'english ivy', 21:'peace lily', 22:'spider plant'}

curs.execute("""
    UPDATE my_table t
    SET furniture = %(t.furniture)s,
    SET plant = %(t.plant)s""",
    d)

原始表看起来有点像这样:

gid | furniture | plant
-----------------------
 0  |    10     |  21
 1  |    11     |  20
 ...

在操作之后,应该如下所示:

gid | furniture |    plant
-----------------------------
 0  |   chair   | peace lily
 1  |   table   | english ivy
 ...

这是可能的,还是我必须在桌子上循环?


Tags: 字典englishpostgresqltableupdatedictniceset
2条回答

catver的方法很有效。然而,我发现创建一个临时表被证明是更有效的。

import psycopg2
from psycopg2.extensions import AsIs

rows = zip(d.keys(), d.values())
curs.execute("""
    CREATE TEMP TABLE codelist(DKEY INTEGER, DVALUE TEXT) 
    ON COMMIT DROP""")

curs.executemany("""
  INSERT INTO codelist (DKEY, DVALUE)
  VALUES(%s, %s)""",
  rows)

for i in [(AsIs('furniture'), AsIs('furniture')), (AsIs('plant'), AsIs('plant'))]:
    curs.execute("""
        UPDATE my_table
        SET %s = codelist.DVALUE
        FROM codelist
        WHERE codelist.DKEY = my_table.%s;
        """, i)

注意:这个例子可能不太有效,因为我正在用TEXT值替换INTEGER。这可能会引发错误ERROR: operator does not exist: integer = character varying。 在这种情况下,this answer可能会有帮助。

试试这个:

rows = (
    {'gid': 10, 'furniture': 10, 'plant': 10},
    {'gid': 20, 'furniture': 20, 'plant': 20}
)
cur.executemany(
    '''
        UPDATE myTable 
        SET
            furniture = %(furniture)s,
            plant = %(plant)s
        WHERE
            gid = %(gid)s
    ''',
    rows
)

相关问题 更多 >

    热门问题