Search code examples
python-3.6cx-oracleindex-error

cursor.fetchall() throws index out or range error


I have an issue which I am not sure where the root cause is:

I use python cx_Oracle to connect to an Oracle DB.

cursor.fetchall() returns me records in this format [(4352,)]

I want to retrieve the '4352' so i proceed to do this: pk = cursor.fetchall()[0][0]

However i get: IndexError: list index out of range

I am not sure what I am doing wrong since when i manually create this return object on my python console as such: item = [(4352,)], I can retrieve the '4352' by calling item[0][0]

Thanks


Solution

  • I figured out what went wrong.

    In my code i did something like this:

    print(cursor.fetchall()) # line 56
    a = cursor.fetchall()[0][0] # line 57
    

    At line 56, the output of [(4352,)] is correct. However at line 57, the cursor.fetchall() becomes a []. This is because cursor.fetchall() is a generator. It has been automatically garbage-collected after line 56.

    Therefore, if I wanted to extract out 4352 from the inner tuple, I had to call line 57 first and subsequently print(a) if I wanted to see the value of the return result from the database.