我有一个文件,其中包含制表符分隔的数据。我逐行拉这个数据并拆分它。然后我在sql查询中使用它来插入表中。遗憾的是,其中一些文件有一个尾随标签(最后一列之后的标签),其中ofc被解释为另一列。当发生这种情况时,我得到一个错误,说sql预期有16个参数并得到17。
运行Python 3.我尝试过使用list理解和过滤器。但它不起作用
....
for line in islice(OutputFile,int(Quantity)):
data= line.split(" ")
#The following line removes ALL values in the list that are empty. This is for the case where there is a trailing tab in the data
data[:] = [val for val in data if val]
query = ("INSERT INTO [smthn].[dbo].smthn] (Country,ChargingType,OrderNumber,foo,bar,foo,bar,foo,bar,foo,bar,foo,bar,foo,Date,bar) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
cursor.execute(query,int(CountryCode),ChargingType,OrderNumber,*data,str(datetime.datetime.now().strftime("%Y-%m-%d")),data[1][:18])
NB。 Cursor.execute是For循环的一部分..不知道为什么这个东西不能把它放在循环中.....
为了公司隐私,我改变了一堆命名。如果有什么东西是间距或命名等关闭,请只是带我在实际代码中正确的面值,当我改变了东西时我可能错过了它。
我应该只接收16个参数的list(因为我从列表中删除了空白项),所以我可以在插入查询中成功执行。
如上所述,错误消息是"The SQL contains 16 parameter markers, but 17 parameters were supplied'"
分析解答
您可以通过以下方式替换data= line.split(" ")
来摆脱尾随标签:
data= line.strip().split(" ")