【问题标题】:saving sensor data raspberry pi to data base将传感器数据树莓派保存到数据库
【发布时间】:2017-08-14 11:28:40
【问题描述】:

我目前正在使用树莓派,并使用 DHT11 每秒读取温度和湿度值。我必须将这些值实时保存到数据库中。 这是我每秒显示传感器数据的代码,我不知道如何以及在何处插入与数据库的连接线。

import RPi.GPIO as GPIO
import dht11
import time
import datetime



# initialize GPIO
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.cleanup()

# read data using pin 7
instance = dht11.DHT11(pin=4)


while True:



    result = instance.read()
    if result.is_valid():
        print("Last valid input: " + str(datetime.datetime.now()))
        print("Temperature: %d C" % result.temperature)
        #print("Temperature: %d F" % ((result.temperature * 9/5) + 32))
        print("Humidity: %d %%" % result.humidity)

time.sleep(1)

【问题讨论】:

    标签: python mysql raspberry-pi


    【解决方案1】:

    首先在您的系统上安装 MySQL db,然后使用 PyMySQL 或任何其他库从 python 连接到 MySQL,如果使用 PyMySQL 则通过 DOC

    使用安装库

    pip install PyMySQL
    

    建立一次连接,因此将连接代码放在您的 while 循环顶部

        db = PyMySQL.connect("localhost:port","username","password","database_name" )
        cursor = db.cursor()
        while True:
    

    在 while 循环中使用游标执行 SQL-QUERY,您可以在其中获得要存储的有效结果

    sql = "insert into table_name(id,feild1,feild2) values (1,value1,value2);"    
    # Execute the SQL command
    cursor.execute(sql)
    # Commit your changes in the database
    db.commit()
    

    将字段表名和连接信息更改为数据库中的字段,并将 INSERT 语句中的值替换为您的传感器值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-01
      • 1970-01-01
      • 2022-01-15
      • 1970-01-01
      • 2022-01-22
      • 2015-05-14
      • 2018-04-16
      • 1970-01-01
      相关资源
      最近更新 更多