-
Notifications
You must be signed in to change notification settings - Fork 2
/
sql_helpers.py
117 lines (105 loc) · 3.34 KB
/
sql_helpers.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
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""All SQL related helper functions to be kept here"""
import sqlite3
class SqlManager:
"""
Class for handling the sql helpers.
Attributes:
-------
database : str
Database path/filename
Methods:
-------
sql_connect():
Creates a new Discord Message
execute_query(query, options):
Helper function for SQL execution when returns are unneeded
execute_query_many(query, options):
Helper function for SQL execution when returns are unneeded
return_query(query, options):
Helper function for SQL execution when returns are needed
"""
def __init__(self, db_name):
"""
Constructs all the necessary attributes for the SqlManager object.
Parameters:
db_name : str
Database path/filename
"""
self.database = db_name
self.sql_connect().close() # create a new DB if it doesn't exist
def sql_connect(self):
"""
Performs the database connection
"""
connection = sqlite3.connect(self.database)
return connection
def execute_query(self, query, options=[]):
"""
Helper function for SQL execution when returns are unneeded.
Parameters:
query : str
SQLite3 query to run
options : list
SQLite3 options
"""
connection = self.sql_connect()
cursor = connection.cursor()
try:
if len(options) == 0:
cursor.execute(query)
else:
cursor.execute(query, options)
connection.commit()
# print("Query successful")
except connection.Error as err:
print(f"Error: '{err}'")
print(f"Query: {query}")
cursor.close()
connection.close()
def execute_query_many(self, query, options=[]):
"""
Helper function for SQL execution of many queries when returns are unneeded.
Parameters:
query : list
SQLite3 queries to run
options : list
SQLite3 options
"""
connection = self.sql_connect()
cursor = connection.cursor()
try:
if len(options) == 0:
cursor.executemany(query)
else:
cursor.executemany(query, options)
connection.commit()
# print("Query successful")
except connection.Error as err:
print(f"Error: '{err}'")
print(f"Many Query: {query}")
cursor.close()
connection.close()
def return_query(self, query, options=[]):
"""
Helper function for SQL execution when returns are needed.
Parameters:
query : str
SQLite3 query to run
options : list
SQLite3 options
"""
connection = self.sql_connect()
cursor = connection.cursor()
try:
if len(options) == 0:
result = cursor.execute(query)
else:
result = cursor.execute(query, options)
result = result.fetchall()
return result
except connection.Error as err:
print(f"Error: '{err}'")
print(f"Return Query: {query}")
cursor.close()
connection.close()
return None