python - SQLAlchemy - 选择更新示例

标签 python sqlalchemy select-for-update

我正在寻找在 SQLAlchemy 中使用 select for update 的完整示例,但尚未找到一个谷歌搜索。我需要锁定一行并更新一列,以下代码不起作用(永远阻塞):

s = table.select(table.c.user=="test",for_update=True)
# Do update or not depending on the row
u = table.update().where(table.c.user=="test")         
u.execute(email="foo") 

我需要提交吗?我怎么做?据我所知你需要: 开始交易 选择...进行更新 更新 提交

最佳答案

如果您使用 ORM,请尝试 with_for_update功能:

foo = session.query(Foo).filter(Foo.id==1234).with_for_update().one()
# this row is now locked

foo.name = 'bar'
session.add(foo)

session.commit()
# this row is now unlocked

关于python - SQLAlchemy - 选择更新示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50506973/

相关文章:

Python-当字典包含重复键时,从字典中选择第一个第一个键值对

python - Postgres+SQLAlchemy 在使用 default=func.now() 时将时间转换为 UTC

python - 在 Python 中使用 SQLAlchemy 连接到 Azure 数据库

mysql - 为什么要使用 SELECT FOR UPDATE? (MySQL)

postgresql - Postgres SELECT ... FOR UPDATE 函数

python - numpy 数组的累积 argmax

Python 多处理错误

mysql - 选择更新

Python+mysql - 在for循环中构建插入语句

python - SQLAlchemy 仅选择一列