我已經創建了一個溫度傳感器(使用DS18B20溫度傳感器)並編寫了python程序,每10秒讀取並顯示一次溫度。它運行良好。後來,我修改了代碼以將每10秒的記錄保存到MySQL數據庫。現在,問題在於它第一次讀取數據時會記錄並上傳數據到數據庫。然後,我收到一條錯誤消息。所以基本上,程序讀取並上傳到數據庫一次,然後在錯誤後退出。 請告訴我如何解決這個問題! 非常感謝!如何以間隔將Python程序中的數據插入MySQL數據庫
下面是代碼:
import os
import time
import MySQLdb
import datetime
i = datetime.datetime.now()
db = MySQLdb.connect(host = "localhost", user = "root", passwd = "bb9125ap", db = "PY1")
cur = db.cursor()
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
temp_sensor = '/sys/bus/w1/devices/28-00042d6745ff/w1_slave'
def temp_raw():
f = open(temp_sensor,'r')
lines = f.readlines()
f.close
return lines
def read_temp():
lines = temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = temp_raw()
temp_output = lines[1].find('t=')
if temp_output != -1:
temp_string = lines[1].strip()[temp_output+2:]
temp_c = float(temp_string)/1000.0
return temp_c
while True:
print "recording data into database(period = 5s.)....press ctrl+Z to stop!"
valT = str(read_temp())
year = str(i.year)
month = str(i.month)
day = str(i.day)
date = day + "-" + month + "-" + year
hour = str(i.hour)
minute = str(i.minute)
second = str(i.second)
time = hour + ":" + minute + ":" + second
try:
cur.execute("""INSERT INTO PY1.DUMP1(temp_c,rec_time,rec_date) VALUES(%s,%s,%s)""",(valT,time,date))
db.commit()
except:
db.rollback()
time.sleep(10)
cur.close()
db.close()
程序名稱是根據我的編輯器db.rollback temp1.py和線54() 以下是錯誤消息我得到
Traceback (most recent call last): File "temp1.py" , line 54 , in time.sleep(10) Attribute:'str' object has no attribute 'sleep'
你會得到什麼錯誤? – Stophface 2015-04-03 09:02:57
Traceback(最近一次調用最後一次):文件「temp1.py」,第54行,在 time.sleep(10)AttributeError:'str'對象沒有屬性'sleep' –
uknowho
2015-04-04 18:18:55
以上是我得到的錯誤消息。然而,該程序將第一次溫度記錄與日期和時間讀數一起保存到數據庫,但之後失敗。並且我不抱歉發佈錯誤信息! – uknowho 2015-04-04 18:22:51