2017-07-19 92 views
1

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

现在,我想批量更新记录,所以我一直在寻找以下问题/回答:https://stackoverflow.com/a/33258295/596841https://stackoverflow.com/a/23324727/596841https://stackoverflow.com/a/39626473/596841,但我不知道如何使用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-16,108264),(... )]

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

我得到的错误是:

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

回答

1

由于Python的元组由Psycopg适用于PostgreSQL的匿名记录,必须指定数据类型:

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

Aaaargh!我曾尝试添加数据类型,但我不小心将它们放在变量之前。 – pookie