且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

SQLAlchemy 核心 - 插入忽略和重复密钥更新

更新时间:2023-01-22 16:45:19

我知道现在有点晚了..但如果有人仍在寻找解决方案.

I know it is a bit late.. but if someone is still looking for solutions.

对于:关于重复密钥更新

ins = insert(/* table_name*/ ).values(/*your values(with PK)*/)
do_update_stmt = ins.on_duplicate_key_update(/*your values(with out PK)*/)
connection.execute(do_update_stmt)

重复关键更新文档

MySQL 支持的 INSERT 的 ON DUPLICATE KEY UPDATE 子句现在支持使用 MySQL 特定的 版本的 Insert 对象

The ON DUPLICATE KEY UPDATE clause of INSERT supported by MySQL is now supported using a MySQL-specific version of the Insert object

这不适用于 sqlalchemy.insert().

对于:插入忽略

这有点麻烦,但效果很好.

This is a bit hacky but works just fine.

 ins_address_stmt = insert(/* table_name*/ ).values(/*your values*/). \
            prefix_with('IGNORE')

插入prefix_with

MySQL 会抑制重复主键的错误并给出警告.

MySQL will suppress the error for duplicate primary key and gives a warning.