列表索引超出Python的范围

2024-09-27 04:22:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我对以下工作有一个问题:

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

在这个函数中,我打印lastrecord.fetchall()[0][0]quantity.get以确保它们是浮动的。所以程序在这种情况下打印:lastrecord.fetchallquantity.get的5.0

到目前为止,没有问题,但当我尝试将它们设置为最大值时,它给了我一个列表索引超出范围的错误,因此程序在我能够成功打印之前找不到lastrecord.fetchall()[0][0]的值,这两行。有人能解释一下原因吗


Tags: runnamefromgetdatetimefloatwherequery
1条回答
网友
1楼 · 发布于 2024-09-27 04:22:06

根据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.

当您第一次使用lastrecord.fetchall()[0][0]lastrecord游标的所有记录都会被提取,因此在第二次调用totalstock = (float(lastrecord.fetchall()[0][0])) + (float(quantity.get()))时,游标没有更多的行了。如果要重用提取的数据,请将其存储,然后随时使用,如下所示:

all_records = lastrecord.fetchall()
// ...
print(float(all_records[0][0]))
// ...
totalstock = (float(all_records[0][0])) + (float(quantity.get()))

相关问题 更多 >

    热门问题