gpd
gpd

Reputation: 180

Getting IndexError: tuple index out of range

I am getting IndexError: tuple index out of range in following code at line 3 if params :

   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()

I am trying to check if the 2nd parameter has been passed to the query or not, if it has been passed then format the sql, sql="select * from {} where fl_id='{}'" and params=("a","b")

Upvotes: 1

Views: 2145

Answers (2)

Tim Mironov
Tim Mironov

Reputation: 859

All you have to do is add * to your formatting statement:

sql.format(*params)

This way you provide an unpacked tuple to the format.

Upvotes: 3

lenik
lenik

Reputation: 23556

You should change your code into something like this:

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

This way you can be sure that you have exactly 2 parameters.

Then you have to pass the tuple elements separately as:

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

because .format() expects two parameters and gets only one, hence the error you get.

Upvotes: 2

Related Questions