-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbhelper.py
73 lines (61 loc) · 2.32 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
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
import pymysql
import dbconfig
import datetime
class DBHelper:
def connect(self, database="crimemap"):
return pymysql.connect(host='localhost', user=dbconfig.db_user, passwd=dbconfig.db_password, db=database)
def get_all_inputs(self):
connection = self.connect()
try:
query = "SELECT description FROM crimes;"
with connection.cursor() as cursor:
cursor.execute(query)
return cursor.fetchall()
finally:
connection.close()
def add_input(self, data):
connection = self.connect()
try:
query = "INSERT INTO crimes (description) VALUES (%s);"
with connection.cursor() as cursor:
cursor.execute(query, data)
connection.commit()
finally:
connection.close()
def clear_all(self):
connection = self.connect()
try:
query = "DELETE FROM crimes;"
with connection.cursor() as cursor:
cursor.execute(query)
connection.commit()
finally:
connection.close()
def add_crime(self, category, date, latitude, longitude, description):
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,
description))
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()