zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

MySQL事务

2023-09-27 14:29:10 时间

https://www.codercto.com/a/86576.html

默认情况,MySQL执行的SQL是autocommit的,SALAlchemy 查询语句也是 autocommit的,就是说如果没有明确声明事务的begin,每个单独的SQL都是一个独立的事务。但是在做交易系统时,比如银行给用户A转账给用户B时,有两个操作,从A里面减100,然后给B加100。这两个操作必须放在一个事务里面才行,否是就会出现钱扣了,对方又没到账的情况。

通过connection.begin 方法可以获取事务对象,执行完sql后,要把事务commit提交,如果出现异常,则把事务rollback,保证数据的最终一致性。

手动开始事务的几种方式:

connection = engine.connect(close_with_result=True)
trans = connection.begin()
try:
    r1 = connection.execute("update account set blance-=100 where id=1")
    r1 = connection.execute("update account set blance+=100 where id=2")
    trans.commit()
except:
    trans.rollback()
    raise
当然,事务还有更优雅的写法,使用上下文管理器的特性,用 with 语句实现

with engine.begin() as connection:
    r1 = connection.execute("update account set blance-=100 where id=1")
    r1 = connection.execute("update account set blance+=100 where id=2")
少了好多行代码,执行完sql会自动提交,如果报异常会自动rollback 。