我是 Python 新手 - 来自 PHP - 并且一直在 Python 官方文档和 SqlAlchemy(我试图像 Laravel 的 DB 类一样轻松地使用它)之间来回切换
我有这段代码:
from sqlalchemy import *
engine = create_engine('mysql://root:<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89f9e8fafab4b4c9e8fefaa7eae6e4" rel="noreferrer noopener nofollow">[email protected]</a>/db')
db_connection = engine.connect()
meta = MetaData()
video_processing = Table('video_processing', meta, autoload=True, autoload_with=engine)
while True:
sleep(1)
stmt = select([video_processing]).where(video_processing.c.finished_processing == 0).where(video_processing.c.in_progress == 0)
result = db_connection.execute(stmt)
rows = result.fetchall()
print len(rows)
stmt = None
result = None
rows = None
当我执行语句时,我让它运行并打印出它获取的行数。 在此过程中,我进入并从数据库中删除行。 问题是,即使我重置了几乎所有我能想到的与查询相关的内容,它仍然在循环的每次迭代中打印出相同数量的获取行,即使我正在更改基础数据。 有什么想法吗?
最佳答案
棘手的部分是,如果将 engine.connect() 与 db_connection.close() 一起使用,则需要关闭连接,否则您可能看不到新的数据更改。
我最终绕过了连接并直接在引擎上执行我的语句,无论如何这在逻辑上更有意义:
result = engine.execute(stmt)
关于python - 使用 SqlAlchemy 在无限循环中获取新结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24687940/