Skip to content
Advertisement

List index out of range for Python

I have a question regarding the following exercise:

def addstock():
        time = datetime.now().strftime("%B %d, %Y")
        hour = datetime.now().strftime("%I:%M%p")
        query = 'SELECT TotalStock FROM Stocks WHERE name = ? ORDER BY MovementID DESC LIMIT 1'
        parameters = (name.get(),)
        lastrecord = run_query(query, parameters)
        print(float(lastrecord.fetchall()[0][0]))
        print(float(quantity.get()))
        totalstock = (float(lastrecord.fetchall()[0][0])) + (float(quantity.get()))
        query = 'SELECT precio FROM product WHERE name = ?'
        precio = run_query(query, parameters)
        pricequant = precio.fetchall()[0]
        pricequantity = pricequant * quantities
        query = 'SELECT precio FROM product WHERE name = ?'
        parameters = (name.get(),)
        precio = run_query(query, parameters)
        priceforall = pricequant * totalstock

In this function, I print lastrecord.fetchall()[0][0] and quantity.get to make sure they are float. So the program prints in that case: 5.0 for lastrecord.fetchall and quantity.get

Up to now, no problem, but when I try to us them up, it gives me an error of List Index Out Of Range, so program do not find the value of lastrecord.fetchall()[0][0] which 2 lines before I was able to print successfully. Can someone explain why?

Advertisement

Answer

According to documentation:

The method fetches all (or all remaining) rows of a query result set and returns a list of tuples. If no more rows are available, it returns an empty list.

When you first time used lastrecord.fetchall()[0][0] all the records of lastrecord curser are fetched, so on the second call on totalstock = (float(lastrecord.fetchall()[0][0])) + (float(quantity.get())) there is no more rows left for the curser. If you want to reuse the fetched data, store it, then use it anytime you want, like this:

all_records = lastrecord.fetchall()
// ...
print(float(all_records[0][0]))
// ...
totalstock = (float(all_records[0][0])) + (float(quantity.get()))
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement