我正在用python開發一個庫存控制系統,當我需要從銀行提取資料以查看它是否已經存在時遇到了問題
這是我的代碼:
import mariadb
banco = mariadb.connect(
host="127.0.0.1",
user="root",
passwd="",
database="controle_estoque"
)
# Ask the user to enter data
textProduto = input("Digite o nome do produto que deseja adicionar ao banco: ")
textQuantidade: int = input("Digite a quantidade: ")
# Ask the user to enter data
# Search the item quantity in the stock database through the product
cursor = banco.cursor()
cursor.execute(f"SELECT produto FROM estoque WHERE produto = '{textProduto}' ")
resultado = cursor.fetchall()[0][0]
print(resultado)
# Search the item quantity in the stock database through the product
# Check if the fields have been filled
if ((textProduto == "") and (textQuantidade == "")):
print("Campos vazios")
# Check if the fields have been filled
# If the product is found, it adds the quantity entered with the quantity in stock
elif resultado == textProduto:
cursor = banco.cursor()
cursor.execute(f"SELECT quantidade FROM estoque WHERE produto = '{resultado}' ")
quantidade_bd = cursor.fetchall()[0][0]
quantidade_final = int(quantidade_bd) int(textQuantidade)
print(quantidade_final)
# If the product is found, it adds the quantity entered with the quantity in stock
# If the product is not found, it inserts the new product into the stock
else:
print("Cadastro realizado")
# If the product is not found, it inserts the new product into the stock
輸出:
Digite o nome do produto que deseja adicionar ao banco:
Digite a quantidade: 100
Traceback (most recent call last):
File "C:/Users/INSS/PycharmProjects/Projeto03/testes/bd.py", line 18, in <module>
resultado = cursor.fetchall()[0][0]
IndexError: list index out of range
Process finished with exit code 1
當我將 textProduct 留空時會發生這種情況。當我在 textProduct 中插入一些東西時,一切正常
我取了這部分更復雜的代碼并以更簡單的方式完成,但錯誤仍然存??在,我搜索了檔案但我不知道如何修復它
uj5u.com熱心網友回復:
您的問題是因為沒有從資料庫回傳結果,還是因為用戶在 textProduct 中輸入了無效輸入?
如果問題是因為資料庫沒有回傳任何內容,您可以將給出錯誤的行包裹在一個Try:塊中,并在一個Except:塊中指示您希望代碼在沒有找到結果時執行的操作。
如果您不希望輸入框允許“”作為輸入,我建議您按照該問題的答案中描述的內容做一些事情: 詢問用戶輸入直到他們給出有效的回應
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/527619.html
