【发布时间】:2017-03-09 21:40:14
【问题描述】:
我查看了具有此IndexError 的类似问题,但没有找到对我的案例的解释。有人可以解释我为什么会收到错误消息吗?
以下代码
mySF2[0]=['000browser', '1', 'Floor', '0.92', '1.74', 'con', 'None']
insertfmt = ' '.join([
"INSERT INTO mySchema.myTable_{}_name (col1, col2, col3, col4, col5, col6)",
"VALUES ({}, {}, NULLIF({},'None')::decimal, NULLIF({},'None')::decimal, {}, NULLIF({},'None')::int)"
])
insertfmt.format(mySF2[0])
给出这个错误
IndexError: tuple index out of range
但是,我计算了 7 个占位符(即大括号 {})和 7 个要输入的项目。那为什么会报错呢?
【问题讨论】:
-
'{}{}'.format([1,2])不起作用。您需要执行'{}{}'.format(*[1,2])来扩展[1,2]。这与'{}{}'.format(1,2)相同 -
同样使用字符串格式来构造查询本质上是不安全的——使用正确的 SQL 接口占位符函数(即单个
?字符并将元组作为额外参数传递给执行或执行许多方法。