Add: ej1 and started ej2

This commit is contained in:
Jose
2026-02-10 02:33:10 +01:00
parent b94c178fb4
commit 9ee0cb6a87
3 changed files with 65 additions and 0 deletions

39
ejercicios/ej2/src/db.py Normal file
View File

@@ -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()

View File

@@ -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]

View File

@@ -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()