venusaur022

导航

SQLAlchemy 2.0 上下文管理

Session Context Managers

Now a session can be instantiated with a context manager, so there is a clear start and end. Here is an example:

with Session() as session:
    session.add(user)
    session.commit()

Here the session is closed when the context manager block ends. And if an error occurs inside it, the session is rolled back.

A variant of this pattern can be used to have a session that automatically commits at the end, while still rolling back on errors:

with Session() as session:
    with session.begin():
        session.add(user)

来源URL

posted on 2023-03-21 15:23  妙蛙花  阅读(70)  评论(0编辑  收藏  举报