I'm developing an inventory control system in python and I had a problem when I need to pull data from the bank to see if it already exists
this is my code:
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
Output:
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
This happens when I leave the textProduct empty. When I insert something in the textProduct everything goes right
I took this part of a more complex code and did it in a simpler way, but the error remains, I searched the documentation but I didn't know how to fix it
CodePudding user response:
Is your problem because no result is being returned from the database or because the user has entered an invalid input into textProduct?
If the issue is because there is nothing returned from the database, you can wrap the line giving you an error in a Try:
block, with an Except:
block instructing what you want the code to do when no result is found.
If you don't want the input box to allow "" as an input, I would suggest you do something along the lines of what is described in the answers to this question: Asking the user for input until they give a valid response