Skip to content
Advertisement

SQLAlchemy Core – Efficient UPSERT of a python list of dictionaries with Mysql

Assuming an existing mysql table, “user”.
Assuming a single column primary key “id”.
Assuming the data to be inserted is always given as a list of dictionaries, in the form:
[{'column_name1':'valueA', 'column_name2':'valueB'}, {'column_name1':'valueC', 'column_name2':'valueD'}].

If a row is inserted with the same primary key (aka id), I’d like to just update the values of all the other columns.

JavaScript

I understand SQLAlchemy does have a on_duplicate_key_update method I could use in sqlalchemy.dialects.mysql.insert. But from the example, I just cannot figure out what my prepare_bulk_upsert_statement function would look like. Ultimately, the content of the user table should look like this:

JavaScript

Looking at the SQLAlchemy example:

JavaScript

It seems on_duplicate_key_update can only handle a row (aka one dictionary). Is there an efficient way to upsert using this method? Or is there a better approach?

Advertisement

Answer

I went with this:

JavaScript

Get the primary key (can be mutiple columns), remove them from the list of columns, use that list to create the dict for on_duplicate_key_update and pass it to execute.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement