Compare commits
2 Commits
ad13cc2121
...
9ee0cb6a87
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9ee0cb6a87 | ||
|
|
b94c178fb4 |
0
ejercicios/.gitkeep
Normal file
0
ejercicios/.gitkeep
Normal file
39
ejercicios/ej2/src/db.py
Normal file
39
ejercicios/ej2/src/db.py
Normal 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()
|
||||
10
ejercicios/ej2/src/files.py
Normal file
10
ejercicios/ej2/src/files.py
Normal 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]
|
||||
16
ejercicios/ej2/src/main.py
Normal file
16
ejercicios/ej2/src/main.py
Normal 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()
|
||||
Reference in New Issue
Block a user