[英]How can I update multiple columns on multiple rows in postgresql using psycopg2
I have a somewhat complex sql query that should update multiple columns on multiple rows in a table. 我有一个稍微复杂的sql查询,该查询应更新表中多个行上的多个列。 Am trying to pass the multiple parameters to the query and also loop though the data to be updated through psycopg2 but I can't figure out a way to do this.
我试图将多个参数传递给查询,并且还会循环通过psycopg2更新数据,但是我不知道该怎么做。
Here is the sample data I want to loop through. 这是我要遍历的示例数据。
data = [(214, 'Feb', 545), (215, 'March', 466)]
So far here is the sql query I have 到目前为止,这里是我有的SQL查询
query = """
UPDATE table_1
SET
date_from =
(CASE version
WHEN 1 THEN '1900-01-01' ELSE
( SELECT date_to
FROM table_1
WHERE month = data.month
AND cust_key = data.cust_key
AND prod_key = data.prod_key
AND version = (
SELECT version-1
FROM table_1
WHERE month = data.month
AND cust_key = data.cust_key
AND prod_key = data.prod_key
ORDER BY version DESC LIMIT 1)
)
END),
date_to = current_date
FROM (VALUES %s) AS data(cust_key, month, prod_key)
WHERE month = data.month
AND cust_key = data.cust_key
AND prod_key = data.prod_key
"""
Here is how I am passing my parameters 这是我传递参数的方式
WHERE month = data.month
AND cust_key = data.cust_key
AND prod_key = data.prod_key
FROM (VALUES %s) AS data(cust_key, month, prod_key)
And this is how I am executing the query 这就是我执行查询的方式
cursor = db.cursor()
execute_values(cursor, query, (data,))
db.commit()
return True
When I execute the query, I get this error psycopg2.errors.InvalidColumnReference: table "data" has 2 columns available but 3 columns specified I have gone through multiple solutions on this site but none seems to work for me. 当我执行查询时,出现此错误psycopg2.errors.InvalidColumnReference:表“数据”有2列可用,但指定了3列我已经在该站点上经历了多种解决方案,但似乎没有一个适合我。
Is there a way around this? 有没有解决的办法?
Your data
is already in the format as expected by psycopg2.extras.execute_values
. 您的
data
已经采用psycopg2.extras.execute_values
期望的格式。
So, do not convert it to another tuple, simply do 因此,不要将其转换为另一个元组,只需执行
execute_values(cursor, query, data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.