【发布时间】:2017-01-01 07:36:48
【问题描述】:
我是 python 的新手,也是 Raspberry Pi 上的编码新手。我正在从传感器读取数据并尝试将其存储在 MySQL 中。我设法设置 MySQL 并创建一个表并手动使用 INSERT INTO 命令来测试数据是否被正确推送并且它似乎工作正常。我在表中设置了两列都是 FLOAT。
我的问题是,当我编写 python 程序来做同样的事情时,它只存储数值而不是 variable 中的值,它实际上包含实时传感器数据。例如,如果我用 python 编写:
sql = "INSERT INTO temp VALUES(12,temperature)"
cursor.execute(sql)
db.commit()
在 MySQL 中会显示:
+-------------------+
| 12 | NULL |
+-------------------+
如您所见,值 12 已存储,但 变量 温度 中的值显示为 NULL。我试图打印温度变量中的值以查看数据,它显示得很好,所以我确定变量温度具有正确的值。我真的不明白为什么我的 python 脚本不会将 variable 的数据发送到 MySQL。
另外,我没有为第一列输入 12,而是尝试创建一个变量 I=I+1,这样每次循环运行时它都会递增,然后我在两列中得到相同的 NULL 值。完整代码如下:
import time
import os
import MySQLdb
# Connect to MySQL
db=MySQLdb.connect("localhost","zikmir","gforce","temprecords")
cursor=db.cursor()
i=0
while True:
# Open the file that we viewed earlier so that python can see what is in it. Replace the serial number as before.
tfile = open("/sys/bus/w1/devices/10-000802824e58/w1_slave")
# Read all of the text in the file.
text = tfile.read()
# Close the file now that the text has been read.
tfile.close()
# Split the text with new lines (\n) and select the second line.
secondline = text.split("\n")[1]
# Split the line into words, referring to the spaces, and select the 10th word (counting from 0).
temperaturedata = secondline.split(" ")[9]
# The first two characters are "t=", so get rid of those and convert the temperature from a string to a number.
temperature = float(temperaturedata[2:])
# Put the decimal point in the right place and display it.
temperature = temperature / 1000
# Display Iteration and Temperature
print i, temperature
i=i+1
# Push data into SQL
sql = "INSERT INTO temp VALUES (i,temperature)"
cursor.execute (sql)
db.commit()
# Wait 5 seconds
time.sleep(5)
任何帮助将不胜感激!
【问题讨论】:
标签: python mysql sql raspberry-pi