python_by_example/sqlite/sql02.py
2023-11-20 01:20:52 -03:00

97 lines
4.1 KiB
Python

from os import getcwd as pwd
import sqlite3
from common.common import clear
def sql_02():
"""Using the PhoneBook database from program 139, write a program that will
display the following menu.
1) View phone book
2) Add to phone book
3) Search for surname
4) Delete person from phone book
5) Quit
If the user selects 1, they should be able to
view the entire phonebook. If they select 2, it should allow them to add a
new person to the phonebook. If they select 3, it should ask them for a
surname and then display only the records of people with the same surname.
If they select 4, it should ask for an ID and then delete that record from
the table. If they select 5, it should end the program. Finally, it should
display a suitable message if they enter an incorrect selection from the menu.
They should return to the menu after each action, until they select 5."""
db_path = f"{pwd()}/sqlite/db/PhoneBox.db"
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS contactos")
query = """CREATE TABLE IF NOT EXISTS contactos(
id integer PRIMARY KEY,
nombre text NOT NULL,
apellido text NOT NULL,
telefono text NOT NULL)"""
cursor.execute(query)
query = """INSERT INTO contactos(nombre, apellido, telefono)
VALUES("Simon", "Howels", "01223 349752"),
("Karen", "Philips", "01954 295773"),
("Darren", "Philips", "01586 749012"),
("Anne", "Philips", "01323 567322"),
("Mark", "Smith", "01223 855534")"""
cursor.execute(query)
def get_data(query):
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
result = cursor.execute(query)
return result
def print_list(data_list):
print("\n ID Nombre Apellido Telefono")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
for x in data_list.fetchall():
print(str(x[0]).ljust(8), x[1].ljust(19), x[2].ljust(15), x[3])
input("\nPresiona Enter para continuar")
def show_all():
query = "SELECT * FROM contactos"
data = get_data(query)
print_list(data)
menu = """
1) Ver libreta de contactos
2) Añadir a libreta
3) Busqueda por apellido
4) Borrar un contacto
s) Salir
"""
keep_in = True
while keep_in:
clear()
print(menu)
sel = input("Ingresa una opción: ")
match sel:
case '1':
show_all()
case '2':
query = "INSERT INTO contactos (nombre, apellido, telefono) "
nombre = input("Ingresa el nombre: ")
apellido = input("Ingresa el apellido: ")
telefono = input("Ingresa el número de teléfono: ")
query += f"values(\"{nombre}\",\"{apellido}\",\"{telefono}\")"
_ = get_data(query)
show_all()
case '3':
search = input("Ingresa parte del apellido a buscar: ")
query = f"SELECT * FROM contactos WHERE apellido LIKE '%{search}%';"
data = get_data(query)
print_list(data)
case '4':
max_sel = get_data("SELECT MAX(id) FROM contactos")
max_sel = int(max_sel.fetchone()[0])
delete = int(input("Ingresa el ID a eliminar: "))
if delete <= max_sel:
query = f"DELETE FROM contactos WHERE id={delete}"
_ = get_data(query)
show_all()
case 's':
keep_in = False
case _:
print("Debes ingresar una opción válida")