2017-07-19 87 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