diff --git a/db.py b/db.py index a159cdc..09b0202 100644 --- a/db.py +++ b/db.py @@ -6,32 +6,30 @@ class VVVVIDatabase(): def __init__(self, path): self.path = path self.is_valid = os.path.isfile(self.path) + self.con = sqlite3.connect(self.path) + + def __del__(self): + self.con.close() def create(self): - con = sqlite3.connect(self.path) - cur = con.cursor() + cur = self.con.cursor() cur.execute("CREATE TABLE series (id INTEGER NOT NULL, name TEXT NOT NULL, season_id INTEGER NOT NULL, type TEXT NOT NULL, PRIMARY KEY (id, season_id));") cur.execute("CREATE TABLE episodes (id INTEGER NOT NULL, serie_id INTEGER NOT NULL, season_id INTEGER NOT NULL, cdn_url TEXT NOT NULL, type TEXT NOT NULL, PRIMARY KEY (id, serie_id, season_id, cdn_url, type));") - con.commit() - con.close() + self.con.commit() def last_serie(self): - con = sqlite3.connect(self.path) - cur = con.cursor() + cur = self.con.cursor() cur.execute("SELECT id FROM series ORDER BY id DESC LIMIT 1;") rows = cur.fetchall() last = (rows[0][0] + 1) if len(rows) > 0 else 0 - con.commit() - con.close() + self.con.commit() return last def series_id(self): - con = sqlite3.connect(self.path) - cur = con.cursor() + cur = self.con.cursor() cur.execute("SELECT id, season_id FROM series ORDER BY id, season_id DESC;") rows = cur.fetchall() - con.commit() - con.close() + self.con.commit() # getting series in a useful format for later series = {} for i, s in rows: @@ -41,12 +39,10 @@ class VVVVIDatabase(): return series def series_episodes(self, serie_id): - con = sqlite3.connect(self.path) - cur = con.cursor() + cur = self.con.cursor() cur.execute("SELECT id, serie_id, season_id FROM episodes ORDER BY id, serie_id, season_id DESC;") rows = cur.fetchall() - con.commit() - con.close() + self.con.commit() # getting series in a useful format for later series = {} for i, s in rows: @@ -56,12 +52,10 @@ class VVVVIDatabase(): return series def insert_serie(self, serie): - con = sqlite3.connect(self.path) - cur = con.cursor() + cur = self.con.cursor() try: cur.execute("INSERT INTO series (id, name, season_id, type) VALUES (?, ?, ?, ?);", serie) - con.commit() - con.close() + self.con.commit() return True except sqlite3.IntegrityError: # serie gia' presente @@ -69,15 +63,11 @@ class VVVVIDatabase(): return False def insert_episodes(self, eps): - con = sqlite3.connect(self.path) - cur = con.cursor() + cur = self.con.cursor() for ep in eps: try: cur.execute("INSERT INTO episodes (id, serie_id, season_id, type, cdn_url) VALUES (?, ?, ?, ?, ?);", ep) - con.commit() - con.close() - return True + self.con.commit() except sqlite3.IntegrityError: # episodi gia' presenti pass - return False