我在我的树莓派上运行 python/mysqldb 时遇到了一些麻烦。这是一个非常简单的脚本,所以我不确定我错过了什么。“SELECT * FROM ...”运行没有问题,但我似乎无法用新值更新表。该脚本运行时不会抛出错误,但是当我 ctrl-C 时,它给了我这个:
异常 _mysql_exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now") in bound method DictCursor.__del of MySQLdb.cursors.DictCursor object at 0x19dfd90
这是我的脚本:
dhost = "localhost"
duser = "root"
dname = "rpi"
dpass = "datPassword"
import MySQLdb
try:
con = MySQLdb.connect(dhost,duser,dpass,dname);
cur = con.cursor(MySQLdb.cursors.DictCursor)
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)
def websiteToSensor():
cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
rows = cur.fetchall()
for row in rows:
cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
return
while True:
websiteToSensor()
有谁知道为什么我的表没有更新?谢谢!
***编辑:解决方案* **
感谢 Martijn Pieters,这是我的新 websiteToSensor() 代码:
def websiteToSensor():
cur = con.cursor(MySQLdb.cursors.DictCursor)
cur.execute("SELECT * FROM homeauto WHERE changedby = 'website'")
rows = cur.fetchall()
num = int(cur.rowcount)
if num > 0:
for row in rows:
cur.execute("UPDATE homeauto SET changedby = 'script' WHERE id = '%s'",(row["id"]))
con.commit()
cur.close()
con.commit()
else:
cur.close()
con.commit()
return