python_by_example/sqlite/sql01.py

37 lines
2.0 KiB
Python
Raw Permalink Normal View History

2023-11-20 01:20:52 -03:00
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])