How to get list using sql query in python?

1k Views Asked by At

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
2

There are 2 best solutions below

1
Stop harming Monica On BEST ANSWER

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.

1
Andomar On

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)