获取索引错误:元组索引超出范围



我在第 3 行if params的以下代码中得到了IndexError: tuple index out of range

def query(self, sql, params=None):
#params in form of a tuple
if params:
sql_new=sql.format(params)
print sql_new
self.cursor.execute(sql_new)
else : self.cursor.execute(sql)
return self.cursor.fetchall()

我正在尝试检查第二个参数是否已传递给查询,如果已传递,则格式化 sql、sql="select * from {} where fl_id='{}'"params=("a","b")

您所要做的就是将*添加到格式化语句中:

sql.format(*params)

这样,您就可以为format提供一个解压缩的元组。

你应该把你的代码改成这样的东西:

#params in form of a tuple
if params and len(params) == 2 :

这样,您可以确定您正好有 2 个参数。

然后,您必须将元组元素分别传递为:

sql_new=sql.format(params[0], params[1])

因为.format()需要两个参数而只得到一个,因此你会得到错误。

最新更新