Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- import sqlite3
- while True:
- print("""
- \nAdministración de la base de datos 'productosPC'
- *-----------------------------------------------*
- | Menú de opciones: |
- | 1) Agregar un nuevo registro |
- | 2) Consultar registros |
- | 3) Borrar registros |
- | 4) Salir |
- *-----------------------------------------------*
- """)
- opcion = input("Ingrese una opcion: ")
- if opcion == '1':
- # validación de los datos
- while True:
- try:
- ID = int(input("Ingrese un ID: "))
- break
- except ValueError:
- print("El ID debe ser un número entero")
- while True:
- nombre = input("Ingrese el nombre del producto: ")
- if len(nombre.strip()) > 0:
- break
- else:
- print("Debe ingresar un nombre válido con algún caracter no vacío")
- while True:
- try:
- precio = int(input("Ingrese un precio: "))
- break
- except ValueError:
- print("El precio debe ser un número entero")
- # guardamos los datos en la base
- conn = sqlite3.connect("productosPC.db")
- cursor = conn.cursor()
- cursor.execute("INSERT INTO productos VALUES (?,?,?)",(ID, nombre, precio))
- conn.commit()
- conn.close()
- print("Se ha guardado el registro")
- elif opcion == '2':
- conn = sqlite3.connect("productosPC.db")
- cursor = conn.cursor()
- cursor.execute("SELECT * FROM productos")
- datos = cursor.fetchall()
- print("ID".rjust(10), "Nombre".rjust(10), "Precio".rjust(10))
- print("\t"+"-"*24)
- if len(datos):
- for dato in datos:
- print()
- for elemento in dato:
- print(str(elemento).rjust(10), end=" ")
- else:
- print("Base de datos vacía")
- conn.close()
- elif opcion == '3':
- while True:
- try:
- id_a_borrar = int(input("Ingrese el ID del producto a borrar: "))
- break
- except ValueError:
- print("El ID debe ser un número entero")
- conn = sqlite3.connect("productosPC.db")
- cursor = conn.cursor()
- cursor.execute("DELETE FROM productos WHERE id = {}".format(id_a_borrar))
- conn.commit()
- conn.close()
- print(f"Se ha borrado el registro con ID = {id_a_borrar}")
- elif opcion == '4':
- print("Gracias por utilizar este programa....")
- break
- else:
- print("Opción incorrecta")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement