从Python dict批量更新PostgreSQL

时间:2015-05-11 07:43:30

标签: python postgresql dictionary psycopg2

在现有的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
 ...

这是可能的还是我必须在表格中循环?

2 个答案:

答案 0 :(得分:4)

试试这个:

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
)

答案 1 :(得分:0)

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)

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

相关问题