【发布时间】:2020-08-01 11:25:00
【问题描述】:
我正在尝试通过 USB 将传感器数据从 Arduino 获取到 RPi,用 Python 读取它并将其插入 MySQL 数据库。即使我尝试插入的数据类型显然是字符串,我也会收到以下错误:
"TypeError: 必须是字符串或只读缓冲区,而不是元组"
我尝试实现的数据库通常有 6 个浮点数,最后有 1 个 int 类型值,但根据其他来源,他们说无论类型应该是什么,数据都应该作为字符串发送。那么我该怎么做才能解决这个问题呢?
我的数据库:
+------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------+------+-----+---------+-------+
| humidity | float | YES | | NULL | |
| temperatur | float | YES | | NULL | |
| lightlevel | float | YES | | NULL | |
| airquality | float | YES | | NULL | |
| lpg | float | YES | | NULL | |
| gas | float | YES | | NULL | |
| pir | int(11) | YES | | NULL | |
+------------+---------+------+-----+---------+-------+
这是我的代码:
import serial
import mysql.connector
import MySQLdb
db = MySQLdb.connect(host = "localhost", user="root", passwd = "password", db = "sensordata")
cur = db.cursor()
ser = serial.Serial('/dev/ttyACM0',9600)
while 1:
serread = ser.readline()
a_list = serread.split()
map_object = map(float, a_list)
list_of_integers = list(map_object)
sql = ("""INSERT INTO datas VALUES (%s,%s,%s,%s,%s,%s,%s)""", (str(list_of_integers[0]), str(list_of_integers[1]), str(list_of_integers[2]), str(list_of_integers[3]), str(list_of_integers[4]), str(list_of_integers[5]), str(list_of_integers[6])))
cur.execute(sql)
db.commit()
print(list_of_integers)
# print(type(str(list_of_integers[0])))
谢谢。
【问题讨论】:
-
您将单个
tuple传递给execute()而不是两个参数。应该是execute(*sql)或execute(sql[0], sql[1]) -
是的。 Execute(*sql) 解决了它。非常感谢!
标签: python mysql arduino raspberry-pi