gpt4 book ai didi

python - 在 MySQL 数据库上保存数据时遇到问题

转载 作者:可可西里 更新时间:2023-11-01 09:00:06 27 4
gpt4 key购买 nike

我是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!"

最佳答案

我明白了,其实很简单,我只是在开头放了一个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!"

关于python - 在 MySQL 数据库上保存数据时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47081748/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com