-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwritetodb.py
39 lines (33 loc) · 1.18 KB
/
writetodb.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
from sense_hat import SenseHat
import pymysql.cursors
import datetime
sense = SenseHat()
sense.clear()
try:
temp = sense.get_temperature()
pressure = sense.get_pressure()
humidity = sense.get_humidity()
except Exception:
print('error getting sensehat temperature')
# Getting data values
string_datetimenow = str(datetime.datetime.now().isoformat())
string_temp = str(temp)
string_pressure = str(pressure)
string_humidity = str(humidity)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='raspberry',
db='weather',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `data` (`date`, `temperature`, `pressure`, `humidity`) VALUES (%s, %s, %s, %s)"
cursor.execute(sql, (string_datetimenow, string_temp, string_pressure, string_humidity))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
finally:
connection.close()