mysql - 插入元组会产生错误 : Not enough arguments for format string

标签 mysql python-3.x

我正在尝试使用 python 3 将通过串行接收的数据插入到 mysql 表中,但是,当我尝试输入插入语句时,我收到“TypeError:格式字符串的参数不足”。任何帮助将不胜感激!

我尝试使用 ", (new_data)" 而不是 "% (new_data)" 并收到 SQL 语法错误。还尝试了 ".format(new_data)" ,它没有产生错误,但导致空字符串字段或 0.00 浮点字段。

raw_data=ser.readline() #Fetch a line from the serial feed

new_data=raw_data.decode('ascii').rstrip()  #Remove extraneous control characters

new_data=(new_data, ) #Convert to a tuple

#Result
#("'2019-5-21 7:55:5',0,3.1,25.6,315,2.2,316,11.0,248,56.6,56.9,0.00,0.73,100375.50,4.37,0.83",)

#Now insert into the database
sql="INSERT INTO reports (rec_time, wnddir, wndspd, wndgust, wndgustdir, wndspdavg2m, wnddiravg2m, wndgustavg10M, wndgustdiravg10M, humidity, tempf, rain, raindly, pressure, battery, light) VALUES ('%s', '%d', '%f', '%f', '%d', '%f', '%d', '%f', '%d', '%f', '%f', '%f', '%f', '%f', '%f', '%f')" % (new_data)
cursor.execute(sql)

我期望将记录写入数据库,但是,我收到“TypeError:格式字符串参数不足”。有16个字段、16个占位符和16条数据。我做错了什么?

最佳答案

There are 16 fields, 16 placeholders and 16 pieces of data.

new_data=(new_data, ) #Convert to a tuple

不,只有 1 元组,而不是 16 元组。

考虑这个例子:

>>> 6,
(6,)

它创建一个 1 元组,包含单个元素 6。 在您的例子中,您创建了一个包含字符串的 1 元组, 其中包含许多字符,包括逗号。 但它仍然是一个 1 元组,因此 .format() 仍在寻找另外 15 个参数。

使用csv模块来迭代你的输入文件, 你会更快乐。

关于mysql - 插入元组会产生错误 : Not enough arguments for format string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56246593/

相关文章:

Python:代码中的查询和MySQL中的查询之间的区别

django - 图像未在 Django 中上传

php - MySQL - 从多个表中选择,可能没有连接?

php - 在 MySQL 中构建用户数据

php - 如果一行不为 null 且不为空,如何显示它?

php - Android:无法使用php pdo在mysql中插入数据

python - 如何使用包含节点和边的 python 字典构建 G Networkx?

scala - Scala 中没有的等价物

python-3.x - 为什么 cv2.COLOR_RGB2GRAY 和 cv2.COLOR_BGR2GRAY 会给出不同的结果?

python - 如何正确抓取基于 JavaScript 的网站?