我正在尝试将python数据插入mysql表中。我正在使用ds18b20温度传感器。我已经尝试了许多教程,但是我不明白如何将mysql添加到用于获取温度数据的python代码中。任何帮助,将不胜感激!现在,我更新了代码,缩进错误消失了。但是,当我执行此代码时,什么也没有发生,并且大于或小于python(>>>)符号是执行我的代码时唯一生成的东西。
这是python:
import os
import glob
import time
import MySQLdb
import datetime
i = datetime.datetime.now()
db = MySQLdb.connect(host = "localhost", user = "root", passwd = "test", db = "temp_pi")
cur = db.cursor()
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.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 TAB_CLASSROOM(temp_c,T_Date,T_Time) VALUES(%s,%s,%s)""",(valT,date,time))
db.commit()
except:
db.rollback()
time.sleep(10)
cur.close()
db.close()
最佳答案
import os
import glob
import time
import MySQLdb
import datetime
i = datetime.datetime.noW()
db = MySQLdb.connect(host = "localhost", user = "root", passwd = "test", db = "temp_pi")
cur = db.cursor()
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28*')[0]
device_file = device_folder + '/w1_slave'
def read_temp_raw():
f = open(device_file, 'r')
lines = f.readlines()
f.close()
return lines
def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != 'YES':
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find('t=')
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.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)
timestring = hour + ":" + minute + ":" + second
try:
cur.execute("""INSERT INTO TAB_CLASSROOM(temp_c,rec_time,rec_date) VALUES(%s,%s,%s)""",(valT,timestring,date))
db.commit()
except:
db.rollback()
time.sleep(10)
cur.close()
db.close()
根据我的编辑,您的WHILE语句未正确缩进。根据pythonm的版本2.7或3.X,您可能需要一会儿,如果它是3.x,则需要在print语句周围加上()。
关于python - 执行此代码时出现python更大或更小的符号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54101186/