+: sqlite3 139-145

This commit is contained in:
devfzn 2023-11-20 01:20:52 -03:00
parent 0cccc5e48c
commit ff699db55a
Signed by: devfzn
GPG Key ID: E070ECF4A754FDB1
18 changed files with 538 additions and 6 deletions

5
.gitignore vendored
View File

@ -1,3 +1,4 @@
__pycache__/ __pycache__/
*/files/*.txt *.txt
*/files/*.csv *.csv
*.db

View File

@ -54,6 +54,16 @@ de *Nichola Lacey*
- [137](./tkgui/tk14.py) - [137](./tkgui/tk14.py)
- [138](./tkgui/tk15.py) - [138](./tkgui/tk15.py)
### Retos SQLite3
- [139](./sqlite/sql01.py)
- [140](./sqlite/sql02.py)
- [141](./sqlite/sql03.py)
- [142](./sqlite/sql04.py)
- [143](./sqlite/sql05.py)
- [144](./sqlite/sql06.py)
- [145](./sqlite/sql07.py)
## Uso ## Uso
```sh ```sh

View File

@ -0,0 +1 @@
directorio para creación/lectura/escritura de archivos

View File

@ -1 +0,0 @@
directorio para los archivos temporales de escritura y lectura

View File

@ -4,6 +4,7 @@ from basic import basic
from trtl import trtl from trtl import trtl
from interm import interm from interm import interm
from tkgui import tkgui from tkgui import tkgui
from sqlite import sqlite
from common.common import clear, user_input, opcs_default from common.common import clear, user_input, opcs_default
def toc(): def toc():
@ -144,8 +145,7 @@ def main():
case 4: case 4:
tkinter_challenges() tkinter_challenges()
case 5: case 5:
#sqlite_challenges() sqlite.challenges()
pass
case 6: case 6:
#final_challenges() #final_challenges()
pass pass

1
sqlite/db/db_directory Normal file
View File

@ -0,0 +1 @@
directorio para bases de datos sqlite3

121
sqlite/examples.py Normal file
View File

@ -0,0 +1,121 @@
import sqlite3
from time import sleep
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS empleados;")
query = """CREATE TABLE IF NOT EXISTS empleados(
id integer PRIMARY KEY,
nombre text NOT NULL,
depto text NOT NULL,
salario integer);"""
cursor.execute(query)
print('1)\n'+query+'\n')
query = """INSERT INTO empleados(id,nombre,depto,salario)
VALUES("1","Bob","Ventas","25000")"""
print('2)\n'+query+'\n')
cursor.execute(query)
db.commit()
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
query = "INSERT INTO empleados(id,nombre,depto,salario) VALUES(?,?,?,?)"
print('3)\n'+query+'\n')
new_id = input("Ingresa el ID: ")
new_name = input("Ingresa el nombre: ")
new_dept = input("Ingresa el departamento: ")
new_salary = input("Enter salary: ")
cursor.execute(query, (new_id,new_name,new_dept,new_salary))
db.commit()
query = "SELECT * FROM empleados"
cursor.execute(query)
print('4)\n'+query+'\n')
print(cursor.fetchall())
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
query = "SELECT * FROM empleados"
print('5)\n'+query+'\n')
cursor.execute(query)
for x in cursor.fetchall():
print(x)
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
query = "SELECT * FROM empleados ORDER BY nombre"
print('6)\n'+query+'\n')
cursor.execute(query)
print("ID".rjust(4), "NOMBRE".ljust(10), "DEPTO".ljust(8), "SUELDO".rjust(6))
for x in cursor.fetchall():
print(str(x[0]).rjust(4), x[1].ljust(10), x[2].ljust(8), str(x[3]).rjust(6))
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
query = "SELECT * FROM empleados WHERE salario>20000"
print('7)\n'+query+'\n')
cursor.execute(query)
print("ID".rjust(4), "NOMBRE".ljust(10), "DEPTO".ljust(8), "SUELDO".rjust(6))
for x in cursor.fetchall():
print(str(x[0]).rjust(4), x[1].ljust(10), x[2].ljust(8), str(x[3]).rjust(6))
query = "SELECT * FROM empleados WHERE depto='Ventas'"
print('8)\n'+query+'\n')
cursor.execute(query)
print("ID".rjust(4), "NOMBRE".ljust(10), "DEPTO".ljust(8), "SUELDO".rjust(6))
for x in cursor.fetchall():
print(str(x[0]).rjust(4), x[1].ljust(10), x[2].ljust(8), str(x[3]).rjust(6))
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS deptos;")
query = """CREATE TABLE IF NOT EXISTS deptos(
id integer PRIMARY KEY,
admin text NOT NULL,
depto text NOT NULL);"""
cursor.execute(query)
sleep(0.1)
query = """INSERT INTO deptos(id,admin,depto)
VALUES("1","Rob","Ventas"),("2", "Zerio","TI")"""
cursor.execute(query)
query = """SELECT empleados.id, empleados.nombre, deptos.admin
FROM empleados, deptos WHERE empleados.depto=deptos.depto
AND empleados.salario >20000"""
print('9)\n'+query+'\n')
cursor.execute(query)
print("ID".rjust(4), "NOMBRE".ljust(10), "ADMIN".ljust(8))
for x in cursor.fetchall():
print(str(x[0]).rjust(4), x[1].ljust(10), x[2].ljust(8))
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
query = "SELECT * FROM empleados WHERE depto=?"
print('10)\n'+query+'\n')
que_depto = input("Ingresa un departmento (Ventas o TI): ")
cursor.execute(query,[que_depto])
print("ID".rjust(4), "NOMBRE".ljust(10), "DEPTO".ljust(8), "SUELDO".rjust(6))
for x in cursor.fetchall():
print(str(x[0]).rjust(4), x[1].ljust(10), x[2].ljust(8), str(x[3]).rjust(6))
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
query = """SELECT empleados.id, empleados.nombre, deptos.admin
FROM empleados, deptos WHERE empleados.depto=deptos.depto;"""
print('11)\n'+query+'\n')
print("ID".rjust(4), "NOMBRE".ljust(10), "ADMIN".ljust(8))
for x in cursor.fetchall():
print(str(x[0]).rjust(4), x[1].ljust(10), x[2].ljust(8))
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
query = "UPDATE empleados SET nombre='Tony' WHERE id=1"
print('11)\n'+query+'\n')
cursor.execute(query)
db.commit()
with sqlite3.connect("./db/compania.db") as db:
cursor = db.cursor()
cursor.execute("SELECT * FROM empleados WHERE id=1")
print(cursor.fetchone())
query = "DELETE FROM empleados WHERE id=1"
print('12)\n'+query+'\n')
cursor.execute(query)
db.commit()

36
sqlite/sql01.py Normal file
View File

@ -0,0 +1,36 @@
from os import getcwd as pwd
import sqlite3
def sql_01():
"""Create an SQL database called PhoneBook that contains a table called
Names with the following data:
ID First Name Surname Phone Number
1 Simon Howels 01223 349752
2 Karen Philips 01954 295773
3 Darren Smith 01586 749012
4 Anne Jones 01323 567322
5 Mark Smith 01223 855534
"""
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)
print("\n ID Nombre Apellido Telefono")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
cursor.execute("SELECT * FROM contactos")
for x in cursor.fetchall():
print(str(x[0]).ljust(8), x[1].ljust(19), x[2].ljust(15), x[3])

96
sqlite/sql02.py Normal file
View File

@ -0,0 +1,96 @@
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")

77
sqlite/sql03.py Normal file
View File

@ -0,0 +1,77 @@
from os import getcwd as pwd
import sqlite3
def sql_03():
"""Create a new SQL database called BookInfo that will store a list of
authors and the books they wrote. It will have two tables. The first one
should be called Authors and contain the following data:
Name Place of Birth
Agatha Christie Torquay
Cecelia Ahern Dublin
J.K. Rowling Bristol
Oscar Wilde Dublin
The second should be called Books and contain the following data:
- Title Author Date Published
1 De Profundis Oscar Wilde 1905
2 Harry Potter and the chamber of secrets J.K. Rowling 1998
3 Harry Potter and the prisioner of Azhkaban J.K. Rowling 1999
4 Lyrebird Cecelia Ahern 2017
5 Murder on the Orient Express Agatha Christie 1934
6 Perfect Cecelia Ahern 2017
7 The marble collector Cecelia Ahern 2016
8 The murder on the links Agatha Christie 1923
9 The picture of Dorian Gray Oscar Wilde 1890
10 The secret adversary Agatha Christie 1921
11 The seven dials mistery Agatha Christie 1929
12 The year I met you Cecelia Ahern 2014"""
db_path = f"{pwd()}/sqlite/db/BookInfo.db"
libros = [
["De Profundis", "Oscar Wilde", "1905"],
["Harry Potter and the chamber of secrets", "J.K. Rowling", "1998"],
["Harry Potter and the prisioner of Azhkaban", "J.K. Rowling", "1999"],
["Lyrebird", "Cecelia Ahern", "2017"],
["Murder on the Orient Express" , "Agatha Christie", "1934"],
["Perfect", "Cecelia Ahern", "2017"],
["The marble collector", "Cecelia Ahern", "2016"],
["The murder on the links", "Agatha Christie", "1923"],
["The picture of Dorian Gray", "Oscar Wilde", "1890"],
["The secret adversary", "Agatha Christie", "1921"],
["The seven dials mistery", "Agatha Christie", "1929"],
["The year I met you", "Cecelia Ahern", "2014"]
]
autores = [
["Agatha Christie", "Torquay"],
["Cecelia Ahern", "Dublin"],
["J.K. Rowling", "Bristol"],
["Oscar Wilde","Dublin"]
]
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS autores")
query = """CREATE TABLE IF NOT EXISTS autores(
id INTEGER PRIMARY KEY,
nombre TEXT NOT NULL,
nacimiento TEXT NOT NULL)"""
cursor.execute(query)
db.commit()
cursor.execute("DROP TABLE IF EXISTS libros")
query = """CREATE TABLE IF NOT EXISTS libros(
id INTEGER PRIMARY KEY,
titulo TEXT NOT NULL,
autor TEXT NOT NULL,
fecha TEXT NOT NULL)"""
cursor.execute(query)
db.commit()
for libro in libros:
query = """INSERT INTO libros(titulo, autor, fecha)
VALUES(?,?,?)"""
cursor.execute(query, [libro[0], libro[1], libro[2]])
db.commit()
for autor in autores:
query = """INSERT INTO autores(nombre, nacimiento)
VALUES(?,?)"""
cursor.execute(query, [autor[0], autor[1]])
db.commit()

24
sqlite/sql04.py Normal file
View File

@ -0,0 +1,24 @@
from os import getcwd as pwd
import sqlite3
def sql_04():
"""Using the BookInfo database from program 141, display the list of authors
and their place of birth. Ask the user to enter a place of birth and then
show the title, date published and authors name for all the books by
authors who were born in the location they selected."""
db_path = f"{pwd()}/sqlite/db/BookInfo.db"
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
cursor.execute("SELECT * FROM autores")
print("\n - Autor Nacimiento")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
for autor in cursor.fetchall():
print(str(autor[0]).ljust(4), autor[1].ljust(20), autor[2].ljust(15))
sel = input("\nIngresa un lugar de nacimiento: ")
query = """SELECT titulo, fecha, nombre FROM libros, autores
WHERE autores.nombre=libros.autor AND autores.nacimiento=?"""
cursor.execute(query, [sel])
print("\n Titulo Publicado Autor")
print("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
for result in cursor.fetchall():
print(result[0].ljust(45), result[1].ljust(10), result[2].ljust(20))

18
sqlite/sql05.py Normal file
View File

@ -0,0 +1,18 @@
from os import getcwd as pwd
import sqlite3
def sql_05():
"""Using the BookInfo database, ask the user to enter a year and display all
the books published after that year, sorted by the year they were published."""
db_path = f"{pwd()}/sqlite/db/BookInfo.db"
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
query = "SELECT * FROM libros WHERE fecha>=? ORDER BY fecha"
sel = input("\nIngresa un año de publicación: ")
cursor.execute(query, [sel])
print("\n - Titulo ", end='')
print(" Autor Publicado")
print("━━━ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━", end='')
print(" ━━━━━━━━━━━━━━━ ━━━━━━━━━━━")
for libro in cursor.fetchall():
print(str(libro[0]).ljust(3), libro[1].ljust(45), libro[2].ljust(15), libro[3])

24
sqlite/sql06.py Normal file
View File

@ -0,0 +1,24 @@
from os import getcwd as pwd
import sqlite3
def sql_06():
"""Using the BookInfo database, ask the user for an author's name and then
save all the books by that author to a text file, with each field
separated by dashes so it looks as follows:
5 - Murder on the Orient Express - Agatha Cristie - 1934
8 - The murder on the links - Agatha Cristie - 1923
....
Open the text file to make sure it has worked correctly."""
db_path = f"{pwd()}/sqlite/db/BookInfo.db"
file_path = f"{pwd()}/sqlite/db/file.txt"
result = []
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
autor = input("\nIngresa el nombre del autor del libro a buscar: ")
query = f"SELECT * FROM libros WHERE autor LIKE '%{autor}%'"
cursor.execute(query)
for libro in cursor.fetchall():
result.append(str(libro[0])+" - "+libro[1]+" - "+libro[2]+" - "+libro[3]+"\n")
with open(file_path, 'w') as file:
file.writelines(result)
print(f"Ruta archivo: {file_path}")

70
sqlite/sql07.py Normal file
View File

@ -0,0 +1,70 @@
from os import getcwd as pwd
import tkinter as tk
import sqlite3
def sql_07():
"""Create a program that displays the following screen:
+---------------------------------------+
| _____________ |
| Enter student's name |_____________| |
| _____________ |
| Enter student's grade |_____________| |
| _________ _________ |
| |___Add___| |__Clear__| |
|_______________________________________|
It should save the data to an SQL database called TestScores when the
Add button is clicked. The Clear button should clear the window."""
db_path = f"{pwd()}/sqlite/db/NotasAlumnos.db"
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS notas (
id INTEGER PRIMARY KEY,
alumno TEXT NOT NULL,
nota FLOAT NOT NULL
)""")
window = tk.Tk()
window.title("Notas Estudiantes")
window.geometry("400x200")
common_bg = "dodger blue"
window["bg"] = common_bg
def save():
with sqlite3.connect(db_path) as db:
cursor = db.cursor()
alumno = in_name.get()
nota = in_grade.get()
query = f"INSERT INTO notas(alumno, nota) VALUES(?,?)"
cursor.execute(query, [alumno, nota])
btn_clear.focus()
def clear():
in_name.delete(0, 'end')
in_grade.delete(0, 'end')
in_name.focus()
lbl_name = tk.Label(text="Nombre", font="Verdana 18")
lbl_name.place(x=30, y=20, width=150, height=40)
lbl_name["bg"] = common_bg
lbl_grade = tk.Label(text="Nota", font="Verdana 18")
lbl_grade.place(x=30, y=70, width=150, height=40)
lbl_grade["bg"] = common_bg
in_name = tk.Entry(font="Verdana 14")
in_name.place(x=180, y=20, width=190, height=40)
in_grade = tk.Entry(font="Verdana 14")
in_grade.place(x=180, y=70, width=190, height=40)
btn_save = tk.Button(text="Guardar", command=save)
btn_save["font"] = "Verdana 16"
btn_save.place(x=30, y=140, width=150, height=45)
btn_clear = tk.Button(text="Limpiar", command=clear)
btn_clear["font"] = "Verdana 16"
btn_clear.place(x=220, y=140, width=150, height=45)
in_name.focus()
window.mainloop()

54
sqlite/sqlite.py Normal file
View File

@ -0,0 +1,54 @@
from . import (
sql01 as ex01,
sql02 as ex02,
sql03 as ex03,
sql04 as ex04,
sql05 as ex05,
sql06 as ex06,
sql07 as ex07,
)
from common.common import (
user_input,
run_func,
print_run_func,
opcs_default,
clear
)
tab = ' '
def challenges():
select_ok = False
while not select_ok:
clear()
print(tab, '1)', ex01.sql_01.__doc__)
print(tab, '2)', ex02.sql_02.__doc__)
print(tab, '3)', ex03.sql_03.__doc__)
print(tab, '4)', ex04.sql_04.__doc__)
print(tab, '5)', ex05.sql_05.__doc__)
print(tab, '6)', ex06.sql_06.__doc__)
print(tab, '7)', ex07.sql_07.__doc__)
opcs_default(1)
selection = user_input(9)
match selection:
case 1:
run_func(ex01.sql_01)
case 2:
run_func(ex02.sql_02)
case 3:
run_func(ex03.sql_03)
case 4:
run_func(ex04.sql_04)
case 5:
run_func(ex05.sql_05)
case 6:
run_func(ex06.sql_06)
case 7:
print_run_func(ex07.sql_07)
case 'v':
return
case 's':
select_ok = True
exit(0)
case _:
continue

View File

@ -0,0 +1 @@
directorio para creación/lectura/escritura de archivos

View File

@ -1 +0,0 @@
directorio para los archivos temporales de escritura y lectura

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.8 KiB