Search code examples
pythonpython-3.xpostgresqlpsycopg

How to get list using sql query in python?


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

Solution

  • 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.