Noa*_*oah 4 python sql locking sqlalchemy
我对如何同时从多个不同进程修改表感到困惑。我尝试过使用Query.with_lockmode(),但它似乎没有达到我期望的效果,这将防止两个进程同时查询相同的行。这是我尝试过的:
import time
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import *
engine = create_engine('mysql://...?charset=utf8&use_unicode=0', pool_recycle=3600, echo=False)
Base = declarative_base(bind=engine)
session = scoped_session(sessionmaker(engine))
class Test(Base):
__tablename__ = "TESTXYZ"
id = Column(Integer, primary_key=True)
x = Column(Integer)
def keepUpdating():
test = session.query(Test).filter(Test.id==1).with_lockmode("update").one()
for counter in range(5):
test.x += 10
print test.x
time.sleep(2)
session.commit()
keepUpdating()
Run Code Online (Sandbox Code Playgroud)
如果我同时运行这个脚本两次,我会得到session.query(Test).filter(Test.id==1).one().x50,而不是 100(假设一开始就是 0),这正是我所希望的。如何让两个进程同时更新值或让第二个进程等待第一个进程完成?