0

I am defining a function here and making a query.

def fetch(temp_pass,temp_accno):
    cur.execute('''SELECT id, name, acc_no, ph_no,address, email,balance
               FROM accounts
               WHERE id = %s and acc_no = %s''',
            (str(temp_pass), str(temp_accno)));
    row = cur.fetchall()
    print(row[2])

In this row should be a list of length 7 but when I run print(row[2]) it gives me error that list index out of range.

This is the error I get

File "Accounting.py", line 13, in fetch
    print(row[2])
IndexError: list index out of range
Andomar
  • 232,371
  • 49
  • 380
  • 404
Eish Ahuja
  • 21
  • 3

2 Answers2

0

row[2] returns the 3rd row of the list of rows. row[0][2] returns the 3rd column of the 1st row.

You could run a snippet like this to visualize what gets returned:

cur.execute(...)
for row in cur:
    print(row)
Andomar
  • 232,371
  • 49
  • 380
  • 404
0

row = cur.fetchall() won't give you a row but a list of rows, so row is not a row at all and row[2] is the third row in the list, not the third field in a row. If you want only a row use cur.fetchone().

Note the the query might return several rows and it is not clear what you want to do in that case so I won't deal with it here. cur.fetchone() will give you only one row anyway.

Stop harming Monica
  • 12,141
  • 1
  • 36
  • 56