我正在循环中运行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()
> OS:ubuntu,
> python:2.7.4
> mysqldb:1.2.3
> mysql:5.5.34