利用python将读取到的数据存入mysql数据库,方便对外提供温湿度数据。

整体代码如下:

import RPi.GPIO as GPIO

import MySQLdb

import dht11

import time

import datetime

db = MySQLdb.connect("localhost", "phpmyadmin", "phpmyadmin", "dht11", charset='utf8' )

cursor = db.cursor()

# initialize GPIO

GPIO.setwarnings(True)

GPIO.setmode(GPIO.BCM)

# read data using pin 14

instance = dht11.DHT11(pin=18)

try:

while True:

result = instance.read()

if result.is_valid():

print("Last valid input: " + str(datetime.datetime.now()))

#print(result.humidity)

print("Temperature: %-3.1f C" % result.temperature)

print("Humidity: %-3.1f %%" % result.humidity)

#有误,请看下面的阐述

sql = """INSERT INTO data(temperature, humidity)

VALUES (result.temperature, result.humidity)"""

try:

cursor.execute(sql)

db.commit()

except:

# Rollback in case there is any error

db.rollback()

time.sleep(6)

except KeyboardInterrupt:

print("Cleanup")

GPIO.cleanup()

db.close()

在实践中发现sql语句执行有问题,居然插入数据失败。

sql = """INSERT INTO data(temperature, humidity)  VALUES (result.temperature, result.humidity)"""

把result.temperature, result.humidity两个值换成具体的数值,比如12.9可以。这两个数据我看了里面的class是float类型,不知道为啥有问题插入不了数据库!再去python操作数据库的知识看了看,原来是sql语句里面是无法识别参数值的,于是修改成这样后就正常了:

sql = """INSERT INTO data(temperature, humidity)

VALUES (%-3.1f, %-3.1f)"""  %  (result.temperature,result.humidity)

数据库结构如下: