2017-05-23 2 views
0

나는 온도/시간 및 온도 데이터를 가져 와서 나중에 SQL 데이터베이스에 게시하려고합니다 (DS18B20 온도 센서 및 라즈베리 파이 3을 사용합니다). pi에 의해 주최되는 웹 사이트 ... 아직 멀지 않았다)파이썬을 사용하여 sqlite3 데이터베이스에 라즈베리 파이 센서 입력

나는 센서 데이터를 읽는 python 스크립트를 발견했으며 잘 동작했다. 그런 다음 SQL 부분을 추가하고 작동하는 것처럼 보이지만 오류가 발생하지는 않습니다. 데이터베이스를 전혀 변경하지 않는 것처럼 보입니다. sqlite3를 데이터베이스가 호출

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 

실제로 테이블을 변경하는 경우 내가 말할 수 없다 (난 그냥 올바른 장소에 찾는 게 아니에요) 또는 그렇지 않은 경우 (내가 잘못된 경우) 온도 .db는 하나의 테이블 "판독 값"만 가지고 있습니다.

저는이 점에서 정말 새롭습니다.

답변

1

삽입 또는 업데이트 문을 사용할 때마다 데이터베이스 변경 내용을 커밋해야합니다. 서버 연결에서 commit()으로 전화하면됩니다.

또 다른 문제는 데이터베이스 연결을 닫는 것입니다. while 루프에서 데이터베이스 연결을 닫으 려하지 않으므로 새 항목을 연결을 닫은 후에 데이터베이스에 삽입 할 수 없으므로 대신 커서 연결을 닫고 새 트랜잭션을 수행해야 할 때마다 새 연결을 만듭니다. 이 문서 here를 읽는다면

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()을 호출하면 마지막 트랜잭션 이후 변경 사항을 커밋하지 않습니다.

데이터베이스에 문제가있는 경우 rollback()을 호출하는 Try-Except 절을 사용하는 것이 더 좋습니다.

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()