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

前端 未结 1 1785
盖世英雄少女心
盖世英雄少女心 2021-02-15 14:34

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

相关标签:
1条回答
  • 2021-02-15 15:09

    This post pointed me in the right direction. The documentation for extras.execute_values also contains a great example using the UPDATE clause.

    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
    )
    
    0 讨论(0)
提交回复
热议问题