我想创建一个循环来存储来自串行数据库的数据。我的代码经历了第一个循环,但未能在下一个循环中执行。这是代码:
import serial
import MySQLdb
import time
dbConn = MySQLdb.connect("localhost","root","root","testing") or die ("could not connect to database")
cursor = dbConn.cursor()
device = '/dev/ttyACM0'
max=30
start=time.time()
while True:
try:
print "Trying...",device
arduino = serial.Serial(device, 9600)
except:
print "Failed to connect on",device
try:
data = arduino.readline()
pieces = data.split("\t")
try:
cursor.execute("INSERT INTO productCount (line,count) VALUES (%s,%s)", (pieces[0],pieces[1]))
dbConn.commit()
cursor.close()
except MySQLdb.IntegrityError:
print "failed to insert data"
#finally:
#cursor.close()
except:
print "Failed to get data from Arduino!"
time.sleep(10)
print "looping..."
remaining=max+start-time.time()
print "%s seconds remaining" % int(remaining)
if remaining<=0:
cursor.close()
break
答案 0 :(得分:1)
你在while循环中关闭了cursor
。在try
和finally
中。将其置于while loop
cursor.close()
把它放在外面,或者把它放在循环中
cursor = dbConn.cursor()