我使用while 1循环读取数据库的一个表内容,当内容改变时,无法实时改变,求大神帮我看下代码
import MySQLdb
import serial
import time
ser = serial.Serial('/dev/ttyACM0',9600,timeout=1)
conn=MySQLdb.connect(host="192.168.191.5",user="root",passwd="123456",db="test")
cursor = conn.cursor()
try:
while 1:
time.sleep(1.5)
n = cursor.execute("select state from t_led")
r = cursor.fetchone()
p = r[0]
ser.write(p)
a = ser.readline()
print r
except KeyboardInterrupt:
conn.close()
ser.close()
cursor.close()
在conn=MySQLdb.connect(host="192.168.191.5",user="root",passwd="123456",db="test")后面之行conn的autocommit(True).
conn=MySQLdb.connect(host="192.168.191.5",user="root",passwd="123456",db="test")
conn.autocommit(True)
Python 中的SQL都是作为事务进行提交,你的事务就是你的查询操作在第一次查询后,一直都没有结束,所以后继的循环次数再多,
对数据库中的实时的数据都是不感知的。建议你在每次的循环后,关闭连接,这样第二次进循环就是重新进行了一次的查询,数据相应的
也就会更新了!
如果不设置autocommit属性为真,你所执行的sql时不会立即提交的。
如何安装MySQLdb????