在这里,我们尝试使用 Arduino Uno 创建一个室温监视器,其中 Arduino 的温度和湿度被带入 Python 程序,通过它我们连接到数据库并在表格中显示数据,但在拆分数据之后它只是抛出无法插入数据错误。
桌子:
湿度温度
56.00 27.00
import serial
import mysql.connector
import time
device = 'COM4' #this will have to be changed to the serial that is
being used
try:
print ("Trying...",device)
arduino = serial.Serial(device, 9600)
except:
print ("Failed to connect on",device )
while True:
try:
time.sleep(2)
data = arduino.readline() //read the data from the arduino
a = data.decode()
print (a)
arr = a.split(" ") //split the data by the tab
h = arr[0]
t = arr[1]
#Here we are going to insert the data into the Database
try:
dbConn = mysql.connector.connect(host="localhost",user="user",password="user",database= "db1" ) or die ("could not connect to database")
cursor = dbConn.cursor()
query = ("""INSERT INTO data (Humidity,Temperature) VALUES (%s,%s)""",(h,t))
cursor.execute(query)
dbConn.commit() #commit the insert
print ("inserted successfully")
cursor.close() #close the cursor
except mysql.connector.Error as error:
print ("failed to insert data")
#finally:
#dbConn.close() #close just incase it failed
except:
print ("error")
/////////////////////////////////////////////// /////////////////// 我们得到的错误是:
尝试... COM4 54.00 26.70
插入数据失败 54.00 26.70
插入数据失败 54.00 26.70
插入数据失败