0

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

2 Answers2

0

You need backticks around a table name that contains - characters.

sql = ("""INSERT INTO `temp-at-interrupt` (Date,Time,Temperature) VALUES (%s,%s,%s )""",(datetimeWrite,temp))

See When to use single quotes, double quotes, and back ticks in MySQL

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

There are couple of things that need to take of.

  1. replace infinite loop while True: to conditional one if True:
  2. Put the try ... except block inside condition #1
  3. Try to debug your execution steps using either pdb or print.

But even you are not able to get the expected result then add the traceback here if any.

MaNKuR
  • 2,578
  • 1
  • 19
  • 31
  • You are passing two value against 3 column . (`Date`,`Time`,`Temperature`) VALUES ('%s','%s','%s' ),(datetimeWrite,temp). Break the `datetimeWrite` into `date` and `time` and pass them separately. – MaNKuR Apr 21 '18 at 04:27
  • Also as suggested by @Barmer print the actual error and for that put the code `cursor.execute(sql)` outside of `try` block – MaNKuR Apr 21 '18 at 04:29
  • Its same . Its write and rollback same time probably . Because it gives `25.35 C 2018-04-20 22:21:04 Writing to Database... Failed writing to database` – Njord Nyström Apr 21 '18 at 13:30