我在第 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()
需要两个参数而只得到一个,因此你会得到错误。