尝试使用查询参数时,需要类似字节的对象而不是 'tuple'

bytes-like object is required not 'tuple' when trying to use query parameters

在 phython 脚本中,我从硬件模块中读取了一个值。我想在 mariadb

中插入这个值

我将硬件值转换为字符串。

wert_float="{:.1f}".format(sensor1)
wert = str(wert_float)

mycursor =mydb.cursor()
sql = "INSERT INTO werte (feuchtigkeit) VALUES (?)", (wert)
mycursor.execute(sql)
mydb.commit()
mycursor.close()
mydb.close()

我也尝试过使用 (%s) 的语句,但在所有尝试中我都遇到了错误:

Traceback (most recent call last):
  File "./waterpi_sql.py", line 118, in <module>
    mycursor.execute(sql)
TypeError: a bytes-like object is required, not 'tuple'

有人可以帮助我吗?

您需要将查询参数移至实际函数参数

sql = "INSERT INTO werte (feuchtigkeit) VALUES (?)"
mycursor.execute(sql, (wert,))

否则,您已将 sql 分配给一个元组,该元组不可执行,并且您编写的方式在我见过的任何文档中均未表达,因此请确保您返回那些