从 Python dict 批量更新 PostgreSQL

n10*_*000 3 python postgresql dictionary psycopg2

在现有的 PostgreSQL 表中,我想要UPDATE几个现有列的值来自字典查找(请参阅下面的字典)。有点像这篇不错的博客文章中描述的那样。但是,我不知道如何使用 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)
Run Code Online (Sandbox Code Playgroud)

最初的表看起来有点像这样:

gid | furniture | plant
-----------------------
 0  |    10     |  21
 1  |    11     |  20
 ...
Run Code Online (Sandbox Code Playgroud)

之后的操作就应该是这样的:

gid | furniture |    plant
-----------------------------
 0  |   chair   | peace lily
 1  |   table   | english ivy
 ...
Run Code Online (Sandbox Code Playgroud)

这是可能的还是我必须遍历表格?

cet*_*ver 8

尝试这个:

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
)
Run Code Online (Sandbox Code Playgroud)