【问题标题】:How can I update multiple columns on multiple rows in postgresql using psycopg2如何使用 psycopg2 更新 postgresql 中多行上的多个列
【发布时间】:2019-06-25 07:37:42
【问题描述】:

我有一个有点复杂的 sql 查询,它应该更新表中多行的多列。我试图将多个参数传递给查询,并通过 psycopg2 循环通过要更新的数据,但我无法找到一种方法来做到这一点。

这是我要循环的示例数据。

 data = [(214, 'Feb', 545), (215, 'March', 466)]

到目前为止,这是我的 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
     """

这是我传递参数的方式

    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)

这就是我执行查询的方式

    cursor = db.cursor()
    execute_values(cursor, query, (data,))
    db.commit()
    return True

当我执行查询时,我得到了这个错误psycopg2.errors.InvalidColumnReference: table "data" has 2 columns available but 3 columns specified 我经历了多个这个网站上的解决方案,但似乎没有一个对我有用。

有没有办法解决这个问题?

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    您的data 已经是psycopg2.extras.execute_values 所期望的格式。

    所以,不要将其转换为另一个元组,只需这样做

    execute_values(cursor, query, data)
    

    【讨论】:

    • 实际上@Kaushik Nayak,我之前尝试过,但它仍然无法正常工作,它会引发另一个错误,提示 UndefinedFunction: operator does not exist: date = text WHERE month = data. month_name它在抱怨“=”符号。
    • @P.Gichia :该错误与从 python 传递数据的方式无关。替换部分与建议的更改完美配合。您必须首先修复查询并查看是否一切正常,通过 postgres 连接(psql/pgadmin 等)登录,然后再使用 python 运行它。如果不能,则必须使用示例数据和表定义询问与查询相关的另一个问题。我的帖子回答了你原来的问题。如果您认为它对您有帮助,请考虑接受它。
    • 你说的很对@Kaushik Nayak,感谢您指出这一点,它运行良好..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-28
    • 2021-09-09
    • 2019-08-27
    • 1970-01-01
    • 1970-01-01
    • 2011-11-19
    • 2021-02-13
    相关资源
    最近更新 更多