我在循环查询 类似下面,发现不能正常执行,只有第一次才能查询到,数据库更新数据后数据不能被select查询到。
import mysql.connector
import time
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="123456",
database="runoob_db"
)
while True:
mycursor = mydb.cursor()
mycursor.execute("SELECT * FROM sites")
myresult = mycursor.fetchall() # fetchall() 获取所有记录
mycursor .close()
time.sleep(2)
for x in myresult:
print(x)
有论坛说关闭游标后需要mydb.commit(),我试了一下确实是可以的,但是我只是查询,没有改变。
这里有个问题,我没有修改数据操作,按道理并没有开启事务,为什么查询不到更新的数据。
查看库文件
\Python37\Lib\site-packages\mysql\connector\connection_cext.py
@property
def autocommit(self):
"""Get whether autocommit is on or off"""
value = self.info_query("SELECT @@session.autocommit")[0]
return True if value == 1 else False
@autocommit.setter
def autocommit(self, value): # pylint: disable=W0221
"""Toggle autocommit"""
try:
self._cmysql.autocommit(value)
self._autocommit = value
except MySQLInterfaceError as exc:
raise errors.get_mysql_exception(msg=exc.msg, errno=exc.errno,
sqlstate=exc.sqlstate)
显示是所有的操作都是默认执行事务的,可以将事务关闭,需要执行修改数据或者更新数据库时候,再调用
mydb.start_transaction()
开启事务就可以了
最简单的办法就是查询完成后手动commit,也可以解决