python mysqldb 清除缓存_在Python中使用MySQLdb的长期陈旧结果

My Python program queries a set of tables in a MySQL DB, sleeps for 30 seconds, then queries them again, etc. The tables in question are continuously updated by a third-party, and (obviously) I would like to see the new results every 30 seconds.

Let's say my query looks like this:

"select * from A where A.key > %d" % maxValueOfKeyFromLastQuery

Regularly I will see that my program stops finding new results after one or two iterations, even though new rows are present in the tables. I know new rows are present in the tables because I can see them when I issue the identical query from interactive mysql (i.e. not from Python).

I found that the problem goes away in Python if I terminate my connection to the database after each query and then establish a new one for the next query.

I thought maybe this could be a server-side caching issue as discussed here: Explicit disable MySQL query cache in some parts of program

However:

When I check the interactive mysql shell, it says that caching is on. (So if this is a caching problem, how come the interactive shell doesn't suffer from it?)

If I explicitly execute SET SESSION query_cache_type = OFF from within my Python program, the problem still occurs.

Creating a new DB connection for each query is the only way I've been able to make the problem go away.

How can I get my queries from Python to see the new results that I know are there?

解决方案

This website and this website contain information on the same problem. In order to keep your tables up to date, you must commit your transactions. Use db.commit() to do this.

As mentioned by the post below me, you can remove the need for this by enabling auto-commit. this can be done by running db.autocommit(True)

Also, auto-commit is enabled in the interactive shell, so this explains why you didn't have the problem there.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值