From 9ee0cb6a875491e0712ee5421d654b98460b4092 Mon Sep 17 00:00:00 2001 From: Jose Date: Tue, 10 Feb 2026 02:33:10 +0100 Subject: [PATCH] Add: ej1 and started ej2 --- ejercicios/ej2/src/db.py | 39 +++++++++++++++++++++++++++++++++++++ ejercicios/ej2/src/files.py | 10 ++++++++++ ejercicios/ej2/src/main.py | 16 +++++++++++++++ 3 files changed, 65 insertions(+) create mode 100644 ejercicios/ej2/src/db.py create mode 100644 ejercicios/ej2/src/files.py create mode 100644 ejercicios/ej2/src/main.py diff --git a/ejercicios/ej2/src/db.py b/ejercicios/ej2/src/db.py new file mode 100644 index 0000000..aee14b5 --- /dev/null +++ b/ejercicios/ej2/src/db.py @@ -0,0 +1,39 @@ +import sqlite3 +from pathlib import Path + +class DBManager: + def __init__(self, path): + self.conn = sqlite3.connect(path) + + def init(self): + try: + with self.conn: + self.conn.execute( + """ + CREATE TABLE IF NOT EXISTS books ( + isbn INTEGER PRIMARY KEY, + title TEXT, + author TEXT, + year DATE, + publisher TEXT + ); + """ + ) + except Exception as e: + print("Error creating table:", e) + + def insert(self, item): + try: + with self.conn: + self.conn.execute( + """ + INSERT INTO books (isbn, title, author, year, publisher) + VALUES (?, ?, ?, ?, ?); + """, + (item.isbn, item.title, item.author, item.year, item.publisher) + ) + except Exception as e: + print("Error inserting book:", e) + + def close(self): + self.conn.close() \ No newline at end of file diff --git a/ejercicios/ej2/src/files.py b/ejercicios/ej2/src/files.py new file mode 100644 index 0000000..1c4dc14 --- /dev/null +++ b/ejercicios/ej2/src/files.py @@ -0,0 +1,10 @@ +import csv +from collections import namedtuple + +nt = namedtuple("Book", ["isbn", "title", "author", "year", "publisher"]) + +def read_file(file): + with open(file, encoding="utf-8") as f: + reader = csv.reader(f, delimiter=";") + next(reader) + return [nt(r[0], r[1], r[2], r[3], r[4]) for r in reader] \ No newline at end of file diff --git a/ejercicios/ej2/src/main.py b/ejercicios/ej2/src/main.py new file mode 100644 index 0000000..5d51024 --- /dev/null +++ b/ejercicios/ej2/src/main.py @@ -0,0 +1,16 @@ +from files import read_file +from db import DBManager +from pathlib import Path + +DATA = Path(__file__).parent.parent / "data" + +def main(): + dbm = DBManager(DATA / "books.bd") + dbm.init() + + file_path = DATA / "books.csv" + for book in read_file(file_path): + dbm.insert(book) + +if __name__ == "__main__": + main() \ No newline at end of file