TAGS :Viewed: 8 - Published at: a few seconds ago

[ Python sqlite loop index out of range ]

dbCursor = dbConnection.execute("SELECT compid, " + rowToUse + ", nameshort, namefull FROM " + tableToUse + " WHERE " + rowToUse + " IS NOT NULL")

dbCursor1 = dbConnection.execute("SELECT compid, " + rowToUse + ", nameshort, namefull FROM " + tableToUse + " WHERE " + rowToUse + " IS NOT NULL")
myList = dbCursor1.fetchall()
myRange = [i for i in range(len(myList))] # [[i] for i in range(len(myList))]

myRangeCurrent = 0

for row1 in dbCursor:
    row = myList[myRange[myRangeCurrent]]
    myRangeCurrent = myRangeCurrent + 1

Gave me:

Traceback (most recent call last):   File "<pyshell#176>", line 1, in
<module>
    row = myList[myRange[myRangeCurrent]] IndexError: list index out of range

Range should last exactly as cycle as was made on same select query. Or not?

Answer 1


Check your SQL queries are correct (hint: you only need one cursor since your queries are the same) and print out the result of fetchall, then try this to print out the rows and their indices.

for i, row in enumerate(dbCursor.fetchall()):
    print(i, row)

Although, you should be able to do this as well

for i, row in enumerate(dbCursor):
    print(i, row)

Answer 2


cricket_007 explained that obtaining len from cursor changes cursor, so I changed code adding one more cursor. Now no more out of range:

mySQL = "SELECT compid, " + rowToUse + ", nameshort, namefull FROM " + tableToUse + " WHERE " + rowToUse + " IS NOT NULL"

dbCursor = dbConnection.execute(mySQL)
dbCursor1 = dbConnection.execute(mySQL)
dbCursor2 = dbConnection.execute(mySQL)

myList = dbCursor1.fetchall()
myList2 = dbCursor2.fetchall()
myRange = list(range(len(myList2)))

myRangeCurrent = 0

for row1 in dbCursor:
    row = myList[myRange[myRangeCurrent]]
    myRangeCurrent = myRangeCurrent + 1