-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.py
More file actions
90 lines (69 loc) · 2.46 KB
/
database.py
File metadata and controls
90 lines (69 loc) · 2.46 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import sqlite3
import init
def initialize():
readSqlFile = open('init.sql', 'r')
sqlFile = readSqlFile.read()
readSqlFile.close()
connection = sqlite3.connect(f"{init.DATABASE_NAME}.db")
cursor = connection.cursor()
connection.execute("PRAGMA foreign_keys = ON;")
cursor.executescript(sqlFile)
connection.commit()
connection.close()
"""
get data from a table titled tableName
returnColumns: the column titles to query (they will be returned)
columnName: the column name to query by (best used with a UNIQUE or PRIMARY KEY value)
inputValue: the value to search for inside of the column titled {columnName}
"""
def queryTableValue(returnColumns, tableName, columnName, inputValue, duplicateResults=False):
connection = sqlite3.connect(f"{init.DATABASE_NAME}.db")
cursor = connection.cursor()
if isinstance(returnColumns, (list, tuple)):
columns = ", ".join(returnColumns)
else:
columns = returnColumns # single column
cursor.execute(
f"SELECT {columns} FROM {tableName} WHERE {columnName} = ?",
(inputValue,)
)
resultMap = {}
result = cursor.fetchall() if duplicateResults else cursor.fetchone()
if not result:
connection.close()
return None
if duplicateResults:
connection.close()
return result
resultMap = dict(zip(returnColumns, result))
connection.close()
return resultMap
def addRowAndReturnRowID(columnValueMap, tableName):
connection = sqlite3.connect(f"{init.DATABASE_NAME}.db")
cursor = connection.cursor()
columns = ", ".join(columnValueMap.keys())
placeholders = ", ".join(["?"] * len(columnValueMap))
values = tuple(columnValueMap.values())
# print(values)
cursor.execute(f""" \
INSERT INTO {tableName} ({columns})
VALUES ({placeholders});
""", values)
cursor.execute("SELECT last_insert_rowid()")
result = cursor.fetchone()
connection.commit()
connection.close()
return result[0]
# This will wipe everything, only use when "the trucks are here"
def TheTrucksAreHere():
connection = sqlite3.connect(f"{init.DATABASE_NAME}.db")
cursor = connection.cursor()
cursor.executescript("""
PRAGMA writable_schema = 1;
DELETE FROM sqlite_master;
PRAGMA writable_schema = 0;
VACUUM;
PRAGMA integrity_check;
""")
connection.commit()
connection.close()