2017-07-19 25 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)、(... )]

最初の値は倍精度で、2番目の値はそれぞれ濃度とROWIDを表す整数です。

私は取得していますエラーは次のとおりです。

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

答えて

1

PythonのタプルがPostgresqlの匿名レコードにPsycopgによって構成されているので、データ型を指定する必要がある:

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

Aaaargh!私は、データ型を追加しようとしたが、私は誤って変数の前に置く... – pookie

関連する問題