Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy Core - INSERT IGNORE and ON DUPLICATE KEY UPDATE

I'm using SQLAlchemy Core with a MySQL database but am having a hard time finding a solution for INSERT IGNORE / DUPLICATE KEY UPDATE. I hate to write a one-off query manually in the code if there's a way to handle this. Most solutions or discussions I've found center around the ORM, but not the core. And even some of those are dead links. Is it even possible?

like image 522
TravisVOX Avatar asked Oct 09 '17 20:10

TravisVOX


People also ask

Is it possible to use SQLAlchemy with on duplicate key update?

The ON DUPLICATE KEY UPDATE clause of INSERT supported by MySQL is now supported using a MySQL-specific version of the Insert object This wont be avaliable with sqlalchemy.insert (). This is a bit hacky but works just fine. MySQL will suppress the error for duplicate primary key and gives a warning. Do you know what data does (values) receive?

Is it possible to use on duplicate key update in MySQL?

The ON DUPLICATE KEY UPDATE clause of INSERT supported by MySQL is now supported using a MySQL-specific version of the Insert object, via sqlalchemy.dialects.mysql.dml.insert () . This Insert subclass adds a new method Insert.on_duplicate_key_update () that implements MySQL’s syntax:

What happened to the UPDATE statement in SQLAlchemy?

The rendered UPDATE statement will emit the SET clause for each referenced column maintaining this order. Deprecated since version 1.4: The update.preserve_parameter_orderparameter will be removed in SQLAlchemy 2.0. Use the Update.ordered_values()method with a list of tuples. New in version 1.0.10. See also

Why is SQLAlchemy returning a different value for each DBAPI?

For DBAPIs which do not natively support returning values (i.e. cx_oracle), SQLAlchemy will approximate this behavior at the result level so that a reasonable amount of behavioral neutrality is provided. Note that not all databases/DBAPIs support RETURNING.


2 Answers

Another method is:

stmt = YourModel.__table__.insert().prefix_with(" ignore").values(data)
session.execute(stmt)
like image 79
buxizhizhoum Avatar answered Nov 05 '22 22:11

buxizhizhoum


shaktimaan's answer works great for MySQL INSERT IGNORE. If you found this page looking for SQLite INSERT IGNORE, remember to do INSERT OR IGNORE

https://www.sqlite.org/lang_insert.html

stmt = insert(/* table_name*/ ).values(/*your values*/).prefix_with('OR IGNORE')
like image 30
Bryan Avatar answered Nov 05 '22 21:11

Bryan