我正在尝试使用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个数据。我在做什么错?
答案 0 :(得分:0)
有16个字段,16个占位符和16个数据。
new_data=(new_data, ) #Convert to a tuple
不,只有1个元组,而不是16个元组。
考虑以下示例:
>>> 6,
(6,)
它将创建一个1元组,其中包含单个元素6。
在您的情况下,您创建了一个包含字符串的1元组,
其中一个字符很多,包括逗号。
但这仍然是1元组,因此.format()
还在寻找另外15个参数。
使用csv
模块遍历您的输入文件,
而且您会更快乐。