-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMySQLconnection.py
42 lines (41 loc) · 2.06 KB
/
MySQLconnection.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
import pymysql.cursors
class MySQLConnection:
def __init__(self, db):
connection = pymysql.connect(host = 'localhost',
user = 'root', # change the user and password as needed
password = 'root',
db = db,
charset = 'utf8mb4',
cursorclass = pymysql.cursors.DictCursor,
autocommit = True)
self.connection = connection
def query_db(self, query, data=None):
with self.connection.cursor() as cursor:
try:
query = cursor.mogrify(query, data)
print("Running Query:", query)
executable = cursor.execute(query, data)
if query.lower().find("insert") >= 0:
# if the query is an insert, return the id of the last row, since that is the row we just added
self.connection.commit()
return cursor.lastrowid
elif query.lower().find("select") >= 0:
# if the query is a select, return everything that is fetched from the database
# the result will be a list of dictionaries
result = cursor.fetchall()
return result
else:
# if the query is not an insert or a select, such as an update or delete, commit the changes
# return nothing
self.connection.commit()
except Exception as e:
# in case the query fails
print("Something went wrong", e)
return False
finally:
# close the connection
self.connection.close()
# this connectToMySQL function creates an instance of MySQLConnection, which will be used by server.py
# connectToMySQL receives the database we're using and uses it to create an instance of MySQLConnection
def connectToMySQL(db):
return MySQLConnection(db)