使用Python(SenseHAT项目)将值发送到数据库

时间:2017-12-11 14:51:12

标签: python mysql raspberry-pi raspbian

我的Raspberry PI 3有一个SenseHAT,我想将一些值发送到外部数据库。

这是我的 .py 文件:

import time
import pymysql.cursors
from sense_hat import SenseHat

sense = SenseHat()

temperature = round(sense.get_temperature(), 1)
pressure = round(sense.get_pressure(), 1)
humidity = round(sense.get_humidity(), 1)

connection = pymysql.connect(host='HOSTNAME',
                             user='USERNAME',
                             password='PASSWORD',
                             db='DATABASE',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

try:
    with connection.cursor() as cursor:

        sql = "INSERT INTO data SET dat_date=%d, dat_time=%d, dat_temperature=%d, dat_pressure=%d, dat_humidity=%d, idx_sensor=%s"
        cursor.execute(sql, (time.strftime("%Y-%m-%d"),time.strftime("%H:%M:%s"),float(temperature),float(pressure),float(humidity),int(1)))

    connection.commit()
finally:
    connection.close()

sense.show_message("T:" + str(temperature) + " P:" + str(pressure) + " H:" + str(humidity), scroll_speed=0.7)

运行SQL查询时出现问题。我在sql中创建了查询,并通过为变量赋值来在下面的行中执行它。但是,即使我更改要插入的值的类型(%s%d),我仍然会出现错误消息。

这是值:

  • dat_date => MySQL日期(2017-12-11)
  • dat_time => MySQL TIME(15:44:54)
  • dat_temperature =>来自SenseHAT的温度(32.6)
  • dat_pressure =>来自SenseHAT的压力(654.98)
  • dat_humidity =>来自SenseHAT的湿度(12.6)
  • idx_sensor =>覆盆子PI ID(在这种情况下 1

以下是错误消息:

Traceback (most recent call last):
  File "sh_sr.py", line 22, in <module>
    cursor.execute(sql, (time.strftime("%Y-%m-%d"),time.strftime("%H:%M:%s"),float(temperature),float(pressure),float(humidity),int(1)))
  File "/home/pi/.local/lib/python2.7/site-packages/pymysql/cursors.py", line 164, in execute
    query = self.mogrify(query, args)
  File "/home/pi/.local/lib/python2.7/site-packages/pymysql/cursors.py", line 143, in mogrify
    query = query % self._escape_args(args, conn)
TypeError: %d format: a number is required, not str

那么,有谁看到我做错了什么?

(这是我第一次用Python开发一些东西。)

我正在使用Raspbian =&gt;上一个版本11.12.2017和PyMySQL与pip

一起安装

1 个答案:

答案 0 :(得分:2)

添加简单引用并使用library(tidyverse) mydf %>% group_by(group_ID) %>% mutate(value2=ifelse(row_number() == 1, 0, value)) %>% mutate(subgroup_ID=lag(value2, default = 0) > 0) %>% mutate(subgroup_ID=cumsum(subgroup_ID)+1) %>% select(-value2) # A tibble: 12 x 4 # Groups: group_ID [3] group_ID element_index value subgroup_ID <dbl> <dbl> <dbl> <dbl> 1 1 1 123 1 2 1 2 0 1 3 1 3 0 1 4 1 4 456 1 5 1 5 214 2 6 2 1 20 1 7 2 2 0 1 8 2 3 30 1 9 3 1 10 1 10 3 2 0 1 11 3 3 10 1 12 3 4 20 2

%s