![](/img/trans.png)
[英]Python - Raspberry pi GPIO to SQlite3 - High/Lov with timestamp
[英]Raspberry pi sensor input to sqlite3 database using python
我正在使用DS18B20温度传感器和树莓派3。我想获取日期/时间和温度数据,并将其放入sql数据库(后来发布到pi托管的网站中……还没有到目前为止)
我找到了一个Python脚本来读取传感器数据,并且运行良好。 然后,我添加了SQL部分,虽然看起来可以正常工作(并且没有出现错误……),但它似乎根本没有改变数据库。 我无法确定它是否实际上是在更改表(并且我只是没有在正确的位置看)还是它没有(以及我哪里出了问题)
import os # import os module
import glob # import glob module
import time # import time module
import sqlite3
conn = sqlite3.connect('Temperature.db')
c = conn.cursor()
os.system('modprobe w1-gpio') # load one wire comm$
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/' # point to the addre$
device_folder = glob.glob(base_dir + '28*')[0] # find device with a$
device_file = device_folder + '/w1_slave' # store the details
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines() # read the device de$
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES': # ignore first line
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=') # find temperature i$
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0 # convert to Celsius
return temp_c
while True:
date= (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
temp=(read_temp())
c.execute("INSERT INTO readings (date,temp) VALUES(?,?)", (date,temp))
conn.close()
break
sqlite3数据库称为Temperature.db,并且只有一个表“ readings”
我真的很新,所以任何建议都将不胜感激。
每当您使用插入或更新语句时,都需要将更改提交到数据库。 您只需在服务器连接上调用commit()
。
另外,另一个问题是您关闭数据库连接。 您不想在while循环中关闭数据库连接,因为自从您关闭与数据库的连接以来,您将无法在数据库中插入新条目。 而是,在需要进行新事务时,关闭游标连接并创建一个新连接。
while True:
c = conn.cursor()
date= (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
temp=(read_temp())
c.execute("INSERT INTO readings (date,temp) VALUES(?,?)", (date,temp))
conn.commit()
c.close()
break
如果您在此处阅读文档,则commit()
函数将提交当前数据库事务。 当您在数据库连接上调用close()
时,它自从上一次事务以来不提交任何更改。
更好的做法是使用Try-Except子句,如果数据库存在问题,该子句将调用rollback()
。
conn = sqlite3.connect('test.db')
try:
cur = conn.cursor()
cur.execute(query, data)
conn.commit()
except Exception as e:
print(e)
conn.rollback()
conn.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.