-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbhelper.py
48 lines (42 loc) · 1.61 KB
/
dbhelper.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
import datetime
import pymysql
import dbconfig
class DBHelper:
def connect(self, database="crimemap"):
print "Getting connection"
return pymysql.connect(host='localhost',
user=dbconfig.db_user,
passwd=dbconfig.db_password,
db=database)
def add_crime(self, category, date, latitude, longitude, desc):
connection = self.connect()
try:
query = "INSERT INTO crimes (category, date, latitude, longitude, description) \
VALUES (%s, %s, %s, %s, %s)"
with connection.cursor() as cursor:
cursor.execute(
query, (category, date, latitude, longitude, desc))
connection.commit()
except Exception as e:
print(e)
finally:
connection.close()
def get_all_crimes(self):
connection = self.connect()
try:
query = "SELECT latitude, longitude, date, category, description FROM crimes;"
with connection.cursor() as cursor:
cursor.execute(query)
named_crimes = []
for crime in cursor:
named_crime = {
'latitude': crime[0],
'longitude': crime[1],
'date': datetime.datetime.strftime(crime[2], '%Y-%m-%d'),
'category': crime[3],
'description': crime[4]
}
named_crimes.append(named_crime)
return named_crimes
finally:
connection.close()