我想知道如何参数化以下 postgres:
UPDATE your_table as t
SET val = x.val_to
FROM ( VALUES
(1, 20),
(3, 44)
) as x (val_from, val_to)
WHERE t.val = x.val_from
AND
your_table.other_id = %(other_id_value)
;
其中
(1, 20), (3, 44)
将使用 psycopg2 进行参数化。
使用:
cur.execute("""
UPDATE your_table as t
SET val = x.val_to
FROM ( VALUES
$(vals)s
) as x (val_from, val_to)
WHERE t.val = x.val_from
AND
your_table.other_id = %(other_id_value)s
;
""", {
'other_id_value' : 3843,
'vals' : [(1, 20), (3, 44)]
}
)
不起作用。
在 psycopg2 https://www.psycopg.org/docs/extras.html 他们有:
>>> execute_values(cur,
... """UPDATE test SET v1 = data.v1 FROM (VALUES %s) AS data (id, v1)
... WHERE test.id = data.id""",
... [(1, 20), (4, 50)])
但是我还需要在那里参数化
data.id
,而不仅仅是 VALUES
。
psycopg2.extras 为此提供了 psycopg2.extras.execute_values 函数。
将 SQL 分成两部分。单独构造 VALUES。连接字符串:
sql_1 = 'UPDATE your_table as t SET val = x.val_to FROM (VALUES'
sql_2 = ') as x (val_from, val_to) WHERE t.val = x.val_from;'
values = (1, 20), (3, 44)
sql = sql_1 + ','.join(map(repr, values)) + sql_2
print(sql)
输出:
UPDATE your_table as t SET val = x.val_to FROM (VALUES(1, 20),(3, 44)) as x (val_from, val_to) WHERE t.val = x.val_from;