MySQLdb是否缓存SELECT结果?

Ber*_*ala 8 python mysql-python

我正在循环中运行SELECT查询.

偶尔,数据库表会更新(由另一个程序).

第一个SELECT检索正确的数据,但循环中的其他调用返回第一个值.

如何检索最新数据?

到目前为止我找到的唯一解决方法是在每次迭代时重新连接到数据库!在我的例子中,取消注释#1#和#2#的注释.仅取消注释#2#是不够的(即重新创建游标),结果仍然被缓存.

这是一个给出错误的工作示例.

import MySQLdb
from time import sleep

class DB:
    def __init__(self):
        self.connection = MySQLdb.connect(mysql_host, mysql_user, mysql_pass, mysql_db)
        self.cursor = self.connection.cursor()

    def get(self):
            sql = ''' SELECT id, message FROM mps_messages
                      WHERE topic=%s ORDER BY id LIMIT 1  '''
            #1# self.connect()
            #2# self.cursor = self.connection.cursor()
            self.cursor.execute(sql, ("topic",) )
            rec = self.cursor.fetchone()
            print rec

    def loop(self):
        while True:
            self.get()
            sleep(4)

db=DB()
db.loop()
Run Code Online (Sandbox Code Playgroud)
  • 操作系统:ubuntu,
  • python:2.7.4
  • mysqldb:1.2.3
  • mysql:5.5.34

Ber*_*ala 12

我不得不补充一下

connection.autocommit(True)
Run Code Online (Sandbox Code Playgroud)

添加SQL_NO_CACHE对所呈现的情况没有影响,显然是因为没有涉及缓存.

我仍然不明白为什么SELECT需要COMMIT.

我会打开一个关于它的新问题.