-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsql_database.py
More file actions
74 lines (48 loc) · 310 KB
/
Copy pathsql_database.py
File metadata and controls
74 lines (48 loc) · 310 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
import sqlite3
import os.path
from sqlite3 import Cursor
from sqlite3 import Connection
def remove_suffix(name_of_table:str,suffix:str):
if name_of_table.find(suffix):
return name_of_table.replace(suffix,"")
return name_of_table
def create_table(name_of_table:str):
"""
Run once!!! to intialise or create a table
"""
#Create sql file and connect to it:
name_of_table = remove_suffix(name_of_table, ".db")
connection = sqlite3.connect(f"{name_of_table}.db")
print(" 1. Opened database file successfully")
# create the table with columns
connection.execute(
f"""CREATE TABLE {name_of_table}
(
DATE DATE NOT NULL,
CATEGORY TEXT NOT NULL,
HOURS INT NOT NULL
)
"""
)
print(" 2. Table created successfully")
return connection
def check_database_exists(name_of_table:str):
name_of_table = remove_suffix(name_of_table, ".db")
if os.path.exists(f"{name_of_table}.db"):
print(f"\nSQL Table: '{name_of_table}.db' Loaded.")
return True
print(f"\nCreating new SQL Table '{name_of_table}.db'")
return False
def load_table(name_of_table) -> list[Connection, Cursor]:
name_of_table = remove_suffix(name_of_table, ".db")
if check_database_exists(name_of_table):
conn = sqlite3.connect(f"{name_of_table}.db")
curs = conn.cursor()
else:
conn = create_table(name_of_table)
curs = conn.cursor()
return [conn, curs]
def add_insert_data(name_of_table:str, connection:Connection, cursor: Cursor, data:tuple):
name_of_table = remove_suffix(name_of_table, ".db")
cursor.execute(f"INSERT INTO {name_of_table} VALUES(?,?,?)", data)
connection.commit()