📜  SQLAlchemy ORM-创建会话

📅  最后修改于: 2020-11-27 07:42:43             🧑  作者: Mango


为了与数据库进行交互,我们需要获取其句柄。会话对象是数据库的句柄。会话类是使用sessionmaker()定义的-一种可配置的会话工厂方法,该方法绑定到之前创建的引擎对象。

from sqlalchemy.orm import sessionmaker
Session = sessionmaker(bind = engine)

然后使用其默认构造函数设置会话对象,如下所示:

session = Session()

下面列出了一些常见的会话类方法-

Sr.No. Method & Description
1

begin()

begins a transaction on this session

2

add()

places an object in the session. Its state is persisted in the database on next flush operation

3

add_all()

adds a collection of objects to the session

4

commit()

flushes all items and any transaction in progress

5

delete()

marks a transaction as deleted

6

execute()

executes a SQL expression

7

expire()

marks attributes of an instance as out of date

8

flush()

flushes all object changes to the database

9

invalidate()

closes the session using connection invalidation

10

rollback()

rolls back the current transaction in progress

11

close()

Closes current session by clearing all items and ending any transaction in progress