Python 循环查询 MySQL - 查询结果未更新? [英] Python loop querying MySQL - query results not updated?

查看:38
本文介绍了Python 循环查询 MySQL - 查询结果未更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些查询 mySQL 的 python 代码,

I've got a small bit of python code that queries mySQL,

while True:
    print "running SQL query"
    cursor.execute('select * from sites where stage="NEW"')
    results = cursor.fetchall() #Fetch results
    for row in results:
        print "change detected" #simplified line for testing
    print "sleeping"
    sleep(10)

当没有记录匹配时输出为:

When no records match output is :

running SQL query
sleeping
running SQL query
sleeping

手动创建匹配的SQL记录(允许循环重复的时间),输出仍然是:

Manually create SQL record that will match (allow time for loop to repeat), output is still :

running SQL query
sleeping
running SQL query
sleeping

停止脚本并重新启动,测试输出如预期:

Stop script and restart, test output is as expected :

running SQL query
change detected
sleeping

所以结果被缓存了?或者查询没有重新运行?

So the results are being cached? or the query not being re-run?

我将如何处理这个问题,记住查询运行非常频繁(我确实想知道关闭数据库连接并每次重新打开,但这似乎过度?)

How would I deal with this, bearing in mind the query is run quite frequently (I did wonder about closing the DB connection and re-opening everytime, but this seems excessive?)

推荐答案

如果你看一下 文档 commit() 它可以提示您的代码为什么不起作用.

If you look the Documentation for commit() it can give a hint on why your code doesn't work.

尝试在 sleep(10) 之后使用 database.commit() 看看它是否有效.

Try using database.commit() after sleep(10) and see if it works.

这篇关于Python 循环查询 MySQL - 查询结果未更新?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆