-
Notifications
You must be signed in to change notification settings - Fork 0
/
mysqlconnection.py
48 lines (42 loc) · 2.03 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
43
44
45
46
47
48
# a cursor is the object we use to interact with the database
import pymysql.cursors
# this class will give us an instance of a connection to our database
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)
# establish the connection to the database
self.connection = connection
# the method to query the database
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:
# INSERT queries will return the ID NUMBER of the row inserted
self.connection.commit()
return cursor.lastrowid
elif query.lower().find("select") >= 0:
# SELECT queries will return the data from the database as a LIST OF DICTIONARIES
result = cursor.fetchall()
return result
else:
# UPDATE and DELETE queries will return nothing
self.connection.commit()
except Exception as e:
# if the query fails the method will return FALSE
print("Something went wrong", e)
return False
finally:
# close the connection
self.connection.close()
# connectToMySQL receives the database we're using and uses it to create an instance of MySQLConnection
def connectToMySQL(db):
return MySQLConnection(db)