【Python】SQLAlchemy:session何时commit,何时close?

SQLAlchemy:session何时commit,何时close?

参考阅读:SQLAlchemy - 官方文档

官方文档说明了关于什么是session,以及如何创建session、如何使用session、如何关闭session

参考阅读 - When do I construct a Session, when do I commit it, and when do I close it?
  1. As a general rule, keep the lifecycle of the session separate and external from functions and objects that access and/or manipulate database data. This will greatly help with achieving a predictable and consistent transactional scope.
    一般来说,将会话的生命周期与访问和/或操作数据库数据的函数和对象分开。这将极大地帮助实现可预测和一致的事务范围。

  2. Make sure you have a clear notion of where transactions begin and end, and keep transactions short, meaning, they end at the series of a sequence of operations, instead of being held open indefinitely.
    确保您对事务在何处开始和结束有一个清晰的概念,并保持事务简短,即它们在一系列操作中结束,而不是无限期地保持打开状态

官方示例

E.g. don’t do this:

### this is the **wrong way to do it** ###

class ThingOne(object):
    def go(self):
        session = Session()
        try:
            session.query(FooBar).update({
   "x": 5})
            session.commit(
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值