38

SQLAlchemy Connection 事务操作

 4 years ago
source link: https://www.tuicool.com/articles/3yimUvR
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

默认情况,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 。

参考链接:

  • https://docs.sqlalchemy.org/en/14/core/connections.html

RFVJny7.jpg!web

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

vQremuy.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK