简体   繁体   English

psycopg2:使用元组元组中的值更新表中的多个行

[英]psycopg2: Update multiple rows in a table with values from a tuple of tuples

I'm attempting to update several rows at once using a tuple of tuples. 我正在尝试使用元组元组一次更新多行。 I figured out how to construct the sql statement from this post , but implementing it in psycopg2 has proven to be more challenging. 我想出了如何从这篇文章构建sql语句,但是在psycopg2实现它已经证明更具挑战性。 Here's what I have: 这就是我所拥有的:

c = db.cursor()

new_values = (("Richard",29),("Ronald",30))

sql = """UPDATE my_table AS t 
         SET name = e.name 
         FROM (VALUES %s) AS e(name, id) 
         WHERE e.id = t.id;"""

c.execute(sql, (new_values,))

The result is an error: ProgrammingError: table "e" has 1 columns available but 2 columns specified This is because the FROM clause is being interpreted as: 结果是错误: ProgrammingError: table "e" has 1 columns available but 2 columns specified这是因为FROM子句被解释为:

FROM (VALUES (("Richard",29),("Ronald",30)))

instead of: 代替:

FROM (VALUES ("Richard",29),("Ronald",30))

I can work around this by doing the following but it seems unsafe: 我可以通过执行以下操作解决此问题,但它似乎不安全:

import re
c = db.cursor()

sql = """UPDATE my_table AS t 
         SET name = e.name 
         FROM (VALUES %s) AS e(name, id) 
         WHERE e.id = t.id;"""
sql = c.mogrify(sql, (new_values,))

# Replace the first occurance of '((' with '('.
sql = sql.replace('((', '(',1)

# Replace the last occurance of '))' with ')'.
sql = re.sub(r'(.*)\)\)', r'\1)', sql)

sql = c.execute(sql)

Is there a better way to do this? 有一个更好的方法吗?

This post pointed me in the right direction. 这篇文章指出了我正确的方向。 The documentation for extras.execute_values also contains a great example using the UPDATE clause. extras.execute_values 的文档还包含一个使用UPDATE子句的好例子。

c = db.cursor()
update_query = """UPDATE my_table AS t 
                  SET name = e.name 
                  FROM (VALUES %s) AS e(name, id) 
                  WHERE e.id = t.id;"""

psycopg2.extras.execute_values (
    c, update_query, new_values, template=None, page_size=100
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM