I have a problem insersting data to my database. I want to write 'TIME'-'DATE'-'TEMPERATURE' values my 'temp-at-interrupt' table. (I'M BEGINNER). I successfuly to get value of temp with date and time. I pass the some function that not neccessary.
Here is my code that i cant find any solution.
import os
import time
import datetime
import glob
import mysql.connector
from mysql.connector import errorcode
from time import strftime
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_dir + '28-000008a43c0e')[0]
device_file = device_folder + '/w1_slave'
#---------------------------------------------------------------------------
#Connect MySQL
#---------------------------------------------------------------------------
cnx = mysql.connector.connect(user='root',password='******',
host='localhost',
database='temp-at-interrupt')
cursor= cnx.cursor()
#---------------------------------------------------------------------------
#Get Temperature Values.
#---------------------------------------------------------------------------
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
return temp_c
#---------------------------------------------------------------------------
#Inset new data
#---------------------------------------------------------------------------
if True:
temp=read_temp()
print(temp)
datetimeWrite = (time.strftime("%Y-%m-%d ") + time.strftime("%H:%M:%S"))
print (datetimeWrite)
#sql= ("""INSERT INTO `temp-at-interrupt` (Date,Time,Temperature) VALUES (%s,%s,%s )""",(datetimeWrite,temp))
sql = ("""INSERT INTO `temp-at-interrupt` (`Date`,`Time`,`Temperature`) VALUES ('%s','%s','%s' )""",(datetimeWrite,temp))
try:
print ("Writing to database...")
# Execute the SQL command
cursor.execute(sql)
# Commit your changes in the database
cnx.commit()
print ("Write Complete")
except:
# Rollback in case there is any error
cursor.close()
cnx.close()
print ("Failed writing to database")
UPDATE I solved my error. I follow the sequence '' You have to set up your connection, define your cursor, run your queries, and after you've finished querying you can close the connection.''
Now I'm very close to get solve my problem. Here what i got output while runnin.
25.35 C
2018-04-20 22:21:04
Writing to Database...
Failed writing to database
Why its give fail. There is no error notification on shell. @MaNKuR @Barmar