-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzfoodDAO.py
More file actions
112 lines (88 loc) · 2.97 KB
/
zfoodDAO.py
File metadata and controls
112 lines (88 loc) · 2.97 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# For interaction with Table = food in Database = datarepresentation
# Modify zstudentDAO -> zfoodDAO
#
# pip install mysql-connector-python
# NOT
# pip install mysql-connector
# https://stackoverflow.com/questions/34168651/what-are-the-differences-between-mysql-connector-python-mysql-connector-python
import mysql.connector
import dbconfig as cfg
# Change class name here
class FoodDAO:
db = ""
#def __init__(self):
def connectToDB(self):
self.db = mysql.connector.connect(
host = cfg.mysql['host'],
user = cfg.mysql['user'],
password = cfg.mysql['password'],
database = cfg.mysql['database']
)
def __init__(self):
self.connectToDB()
# Check for cnxn, if none make one.
def getCursor(self):
if not self.db.is_connected():
self.connectToDB()
return self.db.cursor()
def create(self, values):
cursor = self.getCursor()
sql = "insert into food (category, name, price) values (%s, %s, %s)"
cursor.execute(sql, values)
self.db.commit()
lastRowID = cursor.lastrowid
cursor.close()
return lastRowID
print("create done")
def getAll(self):
cursor = self.getCursor()
sql = "select * from food"
cursor.execute(sql)
results = cursor.fetchall()
# Formatting what comes back from DB
returnArray = []
print(results)
for result in results:
print(result)
returnArray.append(self.convertToDictionary(result))
cursor.close()
return returnArray
print("get all done")
def findByID(self, id):
cursor = self.getCursor()
sql = "select * from food where id = %s"
values = (id, )
cursor.execute(sql, values)
result = cursor.fetchone()
# Format what comes back from db
food = self.convertToDictionary(result)
cursor.close()
return food
def update(self, values):
cursor = self.getCursor()
sql = "update food set category = %s, name = %s, price = %s where id = %s"
cursor.execute(sql, values)
self.db.commit()
print("update done")
cursor.close()
def delete(self, id):
cursor = self.getCursor()
sql = "delete from food where id = %s"
values = (id, )
cursor.execute(sql, values)
self.db.commit()
print("delete done for id", id)
cursor.close()
# Converting tuple returned from DB into dict
def convertToDictionary(self, result):
# List of attributes - match html with colnames
colnames = ['id', 'Category', 'Name', 'Price']
# Empty list
item = {}
# Can't enumerate through an empty result, so check.
if result:
for i, colName in enumerate(colnames):
value = result[i]
item[colName] = value
return item
foodDAO = FoodDAO()