
from sqlalchemy.ext.compiler import compiles import sqlalchemy.sql.expression as expr class Upsert(expr.Insert): pass @compiles(Upsert, "mysql") def compile_upsert(insert_stmt, compiler, **kwargs): if insert_stmt._has_multi_parameters: keys = insert_stmt.parameters[0].keys() else: keys = insert_stmt.parameters.keys() pk = insert_stmt.table.primary_key auto = None if (len(pk.columns) == 1 and isinstance(pk.columns.values()[0].type, sa.Integer) and pk.columns.values()[0].autoincrement): auto = pk.columns.keys()[0] if auto in keys: keys.remove(auto) insert = compiler.visit_insert(insert_stmt, **kwargs) Ondup= 'ON DUPLICATE KEY UPDATE' updates = ', '.join( '%s = VALUES(%s)' % (c.name, c.name) for c in insert_stmt.table.columns if c.name in keys ) if auto is not None: last_id = '%s = LAST_INSERT_ID(%s)' % (auto, auto) if updates: updates = ', '.join((last_id, updates)) else: updates = last_id upsert = ' '.join((insert, ondup, updates)) return upsert try: ###INSERT OR UPDATe db.session.execute(Upsert( BIUserStatistic,rows)) except: print('process_bi_user_statistic_records transaction.rollback()') db.session.rollback() raise else: print('process_bi_user_statistic_records transaction.commit()') 1 Kylin30 2018-12-19 23:50:28 +08:00 我是谁? |
2 hellowang 2018-12-20 08:34:54 +08:00 我在哪? |
3 xpresslink 2018-12-20 10:38:34 +08:00 我要到哪里去? |
4 JQZhang 2018-12-20 10:50:40 +08:00 来 v2 几天我真是膨胀了,连 TM 标题都没看懂就敢进来看看 |
5 fanhaipeng0403 OP @Kylin30 就是 insert 不进去,就更新对应的行。。 |
6 fanhaipeng0403 OP @JQZhang 就是 insert 不进去,就更新对应的行。。 |
7 fanhaipeng0403 OP @xpresslink 就是 insert 不进去,就更新对应的行。。 |
8 JQZhang 2018-12-20 15:07:41 +08:00 @fanhaipeng0403 这个我是真不懂,python 超级白,还是等大神来给解答一下吧 |