gpt4 book ai didi

python - 为什么 ser.readline 数据没有出现在 mysql 中?

转载 作者:行者123 更新时间:2023-11-30 22:18:41 25 4
gpt4 key购买 nike

我正在使用一个连接到 arduino 的传感器,并使用 ser.readline() 来打印传感器的读数和成功。但是当我想使用 ser.readline 将读取值发送到 mysql 时。它只传递设备名称和当前时间,mysql 中显示的读数值为'0'。这是我的编码。

import time
import serial
import smtplib
import datetime
import MySQLdb

db = MySQLdb.connect("192.168.0.103", "fyp", "123456", "system")
ser = serial.Serial('/dev/ttyACM0', 9600)

while True:
api = ser.readline()
current_time = datetime.datetime.now()
print (api)

sql = "INSERT INTO reading (series_no, time, api) VALUES ('test1', current_time, api)"
data = (current_time, api)
cur.execute(sql)

db.close()

使用 %s 也不行。提前谢谢你。

最佳答案

您没有正确地参数化查询。需要解决的几个问题:

  • 为查询参数添加占位符 - %s,周围没有引号
  • data 元组传递给 execute()
  • 提交交易

固定版本:

sql = "INSERT INTO reading (series_no, time, api) VALUES ('test1', %s, %s)"
data = (current_time, api)
cur.execute(sql, data)
db.commit()

关于python - 为什么 ser.readline 数据没有出现在 mysql 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37369333/

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