簡體   English   中英

從數據庫 SQLite3 中獲取沒有索引超出范圍的數據

[英]Get data from database SQLite3 without Index out of range

我需要你的幫助來解決一個問題。 我想用 SQLite3 在數據庫中輸入數據,但首先我需要從那里獲取數據並進行一些計算。 在這里我附上我的代碼:

def run_query(query, parameters = ()):
    with sqlite3.connect(db_name) as conn:
        cursor = conn.cursor()
        result = cursor.execute(query, parameters)
        conn.commit()
    return result

def validation():
    return len(name.get()) != 0 and len(quantity.get()) !=0

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)
        total = lastrecord.fetchall()[0]
        if total is None:
            total = 0
        else:
            total = lastrecord.fetchall()[0]
            total += quantity.get()
        query = 'SELECT precio FROM product WHERE name = ?'
        parameters = (name.get(),)
        precio = run_query(query, parameters)
        pricequantity = precio.fetchall()[0]
        pricequantity *= int(quantity.get())
        query = 'SELECT precio FROM product WHERE name = ?'
        parameters = (name.get(),)
        precio = run_query(query, parameters)
        priceforall = precio.fetchall()[0]
        priceforall *= total

        if validation():
            query = 'INSERT INTO stocks VALUES(NULL, ?, ?, ?, ?, ?, ?, ?)'
            parameters = (name.get(), quantity.get(), pricequantity, total, priceforall, time, hour)
            run_query(query, parameters)
            message = 'Stock for {} added succesfully'.format(name.get())
            name.delete(0, END)
            quantity.delete(0, END)
        else:
            message = 'Name and Quantity required' 

數據庫中有以下數據:

MovementID (整數), Name (文本), Quantity (real), QuantityPrice (real), TotalStock (real), TotalStockPrice (real), time, hour

問題是我收到 lastrecord.fetchall()[0] 的錯誤,它說索引超出范圍,但我不知道為什么。

其他時候,我有一個錯誤,只能將元組(不是“str”)連接到元組。

我不知道如何解決這些問題,因為我是 python 和編程的初學者。

感謝和親切的問候

你不能調用lastrecord.fetchall()兩次。 第一次調用獲取所有剩余的記錄,第二次調用沒有要獲取的內容。

沒有必要調用它兩次。 您已經設置了變量total ,無需再次設置。

也沒有理由調用lastrecord.fetchall()然后對其進行索引。 該查詢有LIMIT 1 ,因此它只會返回一行。 只需調用lastrecord.fetchone()即可獲取該單行。

此外, fetchall()返回一個元組列表。 要獲取totalrecord列的值,您需要對列表和元組進行索引。

lastrecord = run_query(query, parameters)
row = lastrecord.fetchone()
if row:
    total = row[0]
else:
    total = 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM