-
Notifications
You must be signed in to change notification settings - Fork 1
/
Db.py
257 lines (216 loc) · 8.6 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
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
import os
import sqlite3
import mysql.connector
class MySQLDatabase:
def __init__(self):
try:
self.dbconn = mysql.connector.connect(
database=os.environ.get("DB_NAME"),
host=os.environ.get("DB_HOST"),
port=os.environ.get("DB_PORT"),
user=os.environ.get("DB_USER"),
password=os.environ.get("DB_PASS")
)
self.cursor = self.dbconn.cursor(dictionary=True)
except mysql.connector.Error as e:
print(e)
def fetch_all(self, table: str):
try:
query = self.cursor.execute("SELECT * FROM `%s`", table)
rows = self.cursor.fetchall()
return rows
except mysql.connector.Error as e:
print(e)
return False
def fetch_all_by_key(self, table, data: dict):
column = ""
placeholders = "%s"
key_value = ""
for key, value in data.items():
# we need to dynamically build some strings based on the data
# let's generate some placeholders to execute prepared statements
column = "{column_name}".format(column_name=key)
placeholder = "%s"
# let's fill the insert values into a list to use with execute
key_value = value
sql_prepared = "SELECT * FROM `%s` WHERE `%s`=%s" % (
table, column, placeholder)
try:
query = self.cursor.execute(sql_prepared, [value, ])
rows = self.cursor.fetchall()
return rows
except mysql.connector.Error as e:
print(e)
return False
def fetch_single(self, table: str, column_name: str, column_value):
sql_formatted_value = "'{value}'".format(value=column_value)
placeholder = "%s".format(column_name=column_name)
# let's build our query
sql_prepared = "SELECT * FROM `%s` WHERE `%s`=%s" % (
table, column_name, placeholder)
try:
self.cursor.execute(sql_prepared,
[column_value, ])
row = self.cursor.fetchone()
return row
except mysql.connector.Error as e:
print(e)
return False
def insert_single(self, table: str, data: dict):
columns = ""
placeholders = ""
values = []
data_length = len(data)
for index, (key, value) in enumerate(data.items()):
# we need to dynamically build some strings based on the data
# let's generate some placeholders to execute prepared statements
columns += "`{column_name}`".format(column_name=key)
placeholders += "%s"
# let's fill the insert values into a list to use with execute
values.append(value)
# only add a comma if there is another item to assess
if index < (data_length - 1):
columns += ', '
placeholders += ', '
sql_prepared = "INSERT INTO `%s` (%s) VALUES (%s)" % (
table, columns, placeholders)
try:
self.cursor.execute(sql_prepared, values)
self.dbconn.commit()
except mysql.connector.Error as e:
print(e)
return False
def update_single(self, table: str, data: dict, id: int):
update_params = ""
values = []
data_length = len(data)
for index, (key, value) in enumerate(data.items()):
# we need to dynamically build some strings based on the data
# let's generate some placeholders to execute prepared statements
update_params += "`{column_name}`=".format(column_name=key)
update_params += "%s"
# let's fill the insert values into a list to use with execute
values.append(value)
# only add a comma if there is another item to assess
if index < (data_length - 1):
update_params += ', '
# append the id as the last param
values.append(id)
sql_prepared = "UPDATE `%s` SET %s WHERE `id`=%s" % (
table, update_params, '%s')
try:
self.cursor.execute(sql_prepared, values)
self.dbconn.commit()
except mysql.connector.Error as e:
print(e)
return False
def delete_single(self, table: str, id: int):
try:
self.cursor.execute(
"DELETE FROM {table} WHERE `id`=%s".format(table=table), [id, ])
self.dbconn.commit()
except mysql.connector.Error as e:
print(e)
return False
def delete_all(self, table: str):
try:
self.cursor.execute("DELETE FROM {table}".format(table=table))
except mysql.connector.Error as e:
print(e)
return False
def __del__(self):
self.dbconn.close()
class SQLite3Database:
def __init__(self, db: str):
try:
self.conn = sqlite3.connect(db)
self.cursor = self.conn.cursor()
except sqlite3.Error as e:
print(e)
self.__del__
def fetch_all(self, table: str):
try:
query = self.cursor.execute("SELECT * FROM `?`", table)
rows = self.cursor.fetchall()
return rows
except sqlite3.Error as e:
print(e)
return False
def fetch_single(self, table: str, column_name: str, column_value):
sql_formatted_value = "'{value}'".format(value=column_value)
placeholder = ":{column_name}".format(column_name=column_name)
# let's build our query
sql_prepared = "SELECT * FROM `%s` WHERE `%s`=%s" % (
table, column_name, placeholder)
try:
self.cursor.execute(sql_prepared,
[column_value, ])
row = self.cursor.fetchone()
return row
except sqlite3.Error as e:
print(e)
return False
def insert_single(self, table: str, data: dict):
columns = ""
placeholders = ""
values = []
data_length = len(data)
for index, (key, value) in enumerate(data.items()):
# we need to dynamically build some strings based on the data
# let's generate some placeholders to execute prepared statements
columns += "`{column_name}`".format(column_name=key)
placeholders += ":{column_name}".format(column_name=key)
# let's fill the insert values into a list to use with execute
values.append(value)
# only add a comma if there is another item to assess
if index < (data_length - 1):
columns += ', '
placeholders += ', '
sql_prepared = "INSERT INTO `%s` (%s) VALUES (%s)" % (
table, columns, placeholders)
try:
self.cursor.execute(sql_prepared, values)
self.conn.commit()
except sqlite3.Error as e:
print(e)
return False
def update_single(self, table: str, data: dict, id: int):
update_params = ""
values = []
data_length = len(data)
for index, (key, value) in enumerate(data.items()):
# we need to dynamically build some strings based on the data
# let's generate some placeholders to execute prepared statements
update_params += "`{column_name}`=".format(column_name=key)
update_params += ":{column_name}".format(column_name=key)
# let's fill the insert values into a list to use with execute
values.append(value)
# only add a comma if there is another item to assess
if index < (data_length - 1):
update_params += ', '
# append the id as the last param
values.append(id)
sql_prepared = "UPDATE `%s` SET %s WHERE `id`=%s" % (
table, update_params, ':id')
try:
self.cursor.execute(sql_prepared, values)
self.conn.commit()
except sqlite3.Error as e:
print(e)
return False
def delete_single(self, table: str, id: int):
try:
self.cursor.execute(
"DELETE FROM {table} WHERE `id`=?".format(table=table), [id, ])
self.conn.commit()
except sqlite3.Error as e:
print(e)
return False
def delete_all(self, table: str):
try:
self.cursor.execute("DELETE FROM {table}".format(table=table))
except sqlite3.Error as e:
print(e)
return False
def __del__(self):
self.conn.close()