-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdb.py
61 lines (52 loc) · 2.27 KB
/
db.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import sqlite3
from typing import List, Tuple, Any
class SQLiteDB:
def __init__(self, db_name: str , schema_file : str):
self.db_name = db_name
self.connection = None
self.schema_file = schema_file
self.create_table()
def _connect(self):
"""Establish a connection to the SQLite database."""
self.connection = sqlite3.connect(self.db_name)
print(f"Connected to {self.db_name}")
def _disconnect(self):
"""Close the connection to the SQLite database."""
if self.connection:
self.connection.close()
self.connection = None
print(f"Disconnected from {self.db_name}")
def execute_query(self, query: str, params: Tuple = ()) -> None:
"""Execute a single query without returning results (e.g., INSERT, UPDATE, DELETE)."""
try:
self._connect()
with self.connection:
cursor = self.connection.cursor()
cursor.execute(query, params)
self.connection.commit()
print(f"Executed query: {query} with params: {params}")
except Exception as e:
print(f"Error executing query: {query} with params: {params}")
print(f"Error details: {e}")
finally:
self._disconnect()
def fetch_all(self, query: str, params: Tuple = ()) -> List[Tuple[Any]]:
"""Fetch all results from a SELECT query."""
cursor = self.connection.cursor()
cursor.execute(query, params)
results = cursor.fetchall()
print(f"Fetched {len(results)} records from query: {query} with params: {params}")
return results
def fetch_one(self, query: str, params: Tuple = ()) -> Tuple[Any]:
"""Fetch a single result from a SELECT query."""
cursor = self.connection.cursor()
cursor.execute(query, params)
result = cursor.fetchone()
print(f"Fetched one record from query: {query} with params: {params}")
return result
def create_table(self) -> None:
"""Create a table from a CREATE TABLE SQL statement."""
self._connect()
with open( self.schema_file, 'r') as f:
schema_queries = f.read()
self.connection.executescript(schema_queries)