2017-05-23 12 views
0

私はDS18B20温度センサーとラズベリーパイ3を使用しています。日付/時刻と温度のデータを取り込み、SQLデータベースに入れますpiでホストされているウェブサイト...まだ遠くない)Pythonを使用した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 

それが実際にテーブルを変更している場合、私は言うことができない(と私はちょうどいい場所で見ていないよ)、またはそうでない場合は(と私は間違っていた場合) Temperature.dbと1つのテーブル "読み取り値"しかありません

私は本当にこれで新しいので、任意のアドバイスをいただければ幸いです。

答えて

1

InsertステートメントまたはUpdateステートメントを使用するたびに、データベースに変更をコミットする必要があります。サーバー接続で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 

あなたはドキュメントhereを読めば、commit()機能は、現在のデータベースのトランザクションをコミットします。データベース接続でclose()を呼び出すと、最後のトランザクション以降に変更がコミットされません。

データベースに問題がある場合は、rollback()を呼び出すTry-Except句を使用することをお勧めします。

​​
関連する問題