在MySQL数据库上保存数据有问题

时间:2017-11-02 17:56:13

标签: python mysql

我是Python的新手,我正在尝试将串口从Arduino获取的数据保存到MySQL数据库,但我只能保存一次,因为我必须再次运行程序再次保存,我试过了使用while循环,但我只坚持数据库一次,并继续得到“无法从Arduino获取数据!”。

这是我的代码:

import serial
import MySQLdb


dbConn = MySQLdb.connect("localhost","root","sasa","sms") or die ("could not connect to database")
cursor = dbConn.cursor()

device = 'COM3'

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 industrial (db) VALUES (%s)", (pieces[0]))
    dbConn.commit()
    cursor.close()
  except MySQLdb.IntegrityError:
    print "failed to insert data"
  finally:
    cursor.close()
except:
  print "Failed to get data from Arduino!"

1 个答案:

答案 0 :(得分:0)

我已经知道了,实际上它非常简单,我只是在开头放了一个while True:,并且它正确更新,如果有人有兴趣,这里是代码:

import serial
import MySQLdb

while True:
    dbConn = MySQLdb.connect("localhost","root","sasa","sms") or die ("could not connect to database")
    cursor = dbConn.cursor()

    device = 'COM3'


    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 industrial (db) VALUES (%s)", pieces)
        dbConn.commit()
        cursor.close()
      except MySQLdb.IntegrityError:
        print "failed to insert data"
      finally:
        cursor.close()
    except:
      print "Failed to get data from Arduino!"