循环读取数据从串口到数据库

时间:2015-04-16 14:17:42

标签: python mysql

我想创建一个循环来存储来自串行数据库的数据。我的代码经历了第一个循环,但未能在下一个循环中执行。这是代码:

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

1 个答案:

答案 0 :(得分:1)

你在while循环中关闭了cursor。在tryfinally中。将其置于while loop

的中断状态
cursor.close()

把它放在外面,或者把它放在循环中

cursor = dbConn.cursor()