sqlalchemy 的 insert or update

2018-12-19 22:14:17 +08:00
 fanhaipeng0403
  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()')
2438 次点击
所在节点    Python
8 条回复
Kylin30
2018-12-19 23:50:28 +08:00
我是谁?
hellowang
2018-12-20 08:34:54 +08:00
我在哪?
xpresslink
2018-12-20 10:38:34 +08:00
我要到哪里去?
JQZhang
2018-12-20 10:50:40 +08:00
来 v2 几天我真是膨胀了,连 TM 标题都没看懂就敢进来看看
fanhaipeng0403
2018-12-20 11:47:28 +08:00
@Kylin30 就是 insert 不进去,就更新对应的行。。
fanhaipeng0403
2018-12-20 11:47:34 +08:00
@JQZhang 就是 insert 不进去,就更新对应的行。。
fanhaipeng0403
2018-12-20 11:47:40 +08:00
@xpresslink 就是 insert 不进去,就更新对应的行。。
JQZhang
2018-12-20 15:07:41 +08:00
@fanhaipeng0403 这个我是真不懂,python 超级白,还是等大神来给解答一下吧😂

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/519151

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX