[Python] Batch Update to postgreSQL table using psycopg2

Discussão em 'Python' iniciado por Stack, Março 20, 2025.

  1. Stack

    Stack Membro Participativo

    In my python code, I have a list of dictionaries which I want to update the database with. However, I want to use the mogrify() method in psycopg2 to convert this data to a query string that I can use with the execute() method so that the update can be executed more efficiently(as opppose to executemany()). My problem is that I have to convert the list of dictionaries into a list of tuples to be compatible with mogrify.

    The problem is I do not know how to use the where clause in the query when I can no longer index based on the 'id' key.

    I want to update the row in the db table based on the value of the id in the python data and the db data being the same. When I have a list of tuples, I am using mogrgify to convert this into a string, how do I execute the UPDATE where the value of the id in the list of tuples is equal to the corresponding id in the db table?

    I tried the update statement but the id values were getting updated as well.

    this is the data im trying to update the db with(user_data is a list of tuples)

    args = ','.join(crsr.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", i).decode('utf-8') for i in user_data)


    if the ids are the 1st 2nd value in each row, how would I update the table based on it matching this value and the row in the table with this value

    Continue reading...

Compartilhe esta Página