Sqlalchemy Upsert

实现不存在则插入

1
2
3
4
5
6
7
8
def upsert(table, insert_data: dict, update_data: dict):
"""
插入或者更新
"""
insert_stmt = insert(table).values(**insert_data)
on_duplicate_key_stmt = insert_stmt.on_duplicate_key_update(**update_data)
with db.engine.connect() as connect:
connect.execute(on_duplicate_key_stmt)
1
2
3
4
5
6
7
8
def ignore_insert(table, data: dict):
"""
忽略重复插入
"""
insert_command = table.__table__.insert().prefix_with(' IGNORE').values(data)
with db.engine.connect() as connect:
connect.execute(insert_command)
connect.commit()