Return on screen a database information with Python

Asked

Viewed 73 times

-1

I have the following code:

# Lista dos produtos

produtos = {'1':('Dipirona 500mg 10 cp', 2.99),
            '2':('Paracetamol 500mg 10 cp', 4.7),
            '3':('Ibuprofeno 600 mg 4 cp ', 5.98),
            '4':('Dorflex 10 cp', 10.99),
            '5':('Neosoro', 3.49),
            '6':('Torsilax 4 cp', 5.99)}

total_compra = valor_item = troco = 0 # variável para total da compra, valor unitário do item e para o troco
produtos_comprados = [] # lista que receberá os itens 'escaneados'/digitados
qtd_produtos = 0 # variável que recebe a quantidade de produtos


while True:
  codigo = str(input('\nDigite o código de um produto: '))
  if len(codigo) > 0:
    if codigo in produtos.keys():
      print(f'Produto.: {produtos.get(codigo)[0]}')
      descricao_produto = produtos.get(codigo)[0]
      print(f'Valor...: R$ {produtos.get(codigo)[1]:.2f}')
      valor_pro = produtos.get(codigo)[1]
      qtd_produtos += 1
      total_compra += valor_pro
      produtos_comprados.append([codigo, valor_pro, descricao_produto])
    else:
      print('Código de produto inválido')
  else:
    break

It’s working normally, only now I want this same code to query the MYSQL database (instead of consulting the dictionary). I have already created the table and database in MYSQL, I have installed the MYSQL connector via Pip, I have already made the import and connection to the database. I just really wanted to know how to write the syntax of how it looks in the bank and returns the product name and price. Then, I need him to add the searched items to a local list, because the purchased items will be shown on the invoice on the screen.

In the table I have the same fields: code (integer) , product(varchar) and price(float). When entering the code, I need it to return the product and the price on the screen. Thank you for your attention and help.

1 answer

1

Let’s walk

Install the library

pip install mysql-connector-python

Connecting to the bank

import mysql.connector

mydb = mysql.connector.connect(
  host="db_host",
  user="usuario",
  password="senha"
)

cursor = mydb.cursor()

Accessing the data

codigo = input('\nDigite o código de um produto: ')   # Nao precisa do str()
sql = f"select produto, preco from produtos where codigo = '{codigo}';"

cursor.execute(sql)

for (produto, preco) in cursor:
    print(produto, preco)

Updating had forgotten the from produtos (from table)

Note Take a look at fetchall() and fetchone()

Closing connection with bank

cursor.close()
mydb.close()
  • 1

    Answered in the post

  • Hi Paulo Marques, all right? Didn’t understand this formatted string sql = f"select product, preco Where code = '{code}';" . How will it select within a format string? it will return the literal text not? Either way, you are giving the following error: mysql.connector.errors.Programmingerror: 1054 (42S22): Unknown column 'product' in 'field list'

  • Code in git (no database connection) if you want to check https://gist.github.com/jonathasfrsantos/ae00deb04e53f1794017a128707bd728

  • Oops, I had forgotten the from table in the query. I updated the post. The query is executed on the line cursor.execute(sql) you can put the string right there.

  • It worked buddy! Now I need it to include the searched items in a list called "purchased products". I have no idea how to create variables where it gets "product name" and "price" and then take these values and insert them into a list.

  • Better open another post with this question.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.