1

I have this piece of code that collects data from a HAT connected to a Raspberry. When run it gives this error:

[51.57, 22.30, 1002.01]
Traceback (most recent call last):
  File "dbWriter.py", line 45, in <module>
    write2DB(record)
  File "dbWriter.py", line 26, in write2DB
    assert len(values) == 3
AssertionError

I am by no means a programmer, i just fiddle around. It is meant to save 'record' to a database, which is then read and updated in realtime on an apache2 server. All help appreciated.

import mysql.connector
from itertools import repeat
import sys
import bme680
import time

try:
   sensor = bme680.BME680(bme680.I2C_ADDR_PRIMARY)
except IOError:
   sensor = bme680.BME680(bme680.I2C_ADDR_SECONDARY)

sensor.set_humidity_oversample(bme680.OS_2X)
sensor.set_pressure_oversample(bme680.OS_4X)
sensor.set_temperature_oversample(bme680.OS_8X)
sensor.set_filter(bme680.FILTER_SIZE_3)

mydb = mysql.connector.connect(
    host='localhost',
    user='pi',
    passwd='pass',
    database='weatherDB'
)
mycursor = mydb.cursor()

def write2DB(values):
    assert len(values) == 3
    sqlText = '''INSERT INTO data(humidity, temperature, pressure) VALUES({},{}, })'''.format(values[0], values[1], values[2])
    mycursor.execute(sqlText)
    mydb.commit()

for _ in repeat(None):
   sensor.get_sensor_data()
   output_humi = '{0:.2f}'.format(
       sensor.data.humidity)
   output_temp = '{0:.2f}'.format(
       sensor.data.temperature)
   output_pres = '{0:.2f}'.format(
       sensor.data.pressure)
   record = []
   record = ('[' + (output_humi) + ', ' + (output_temp) + ', ' + (output_pres) + ']')
   print(record)
   write2DB(record)
   time.sleep(10)
   pass

1 Answer 1

1

You have:

record = ('[' + (output_humi) + ', ' + (output_temp) + ', ' + (output_pres) + ']')

record evaluates to a single string, not a list of 3 elements and hence your exception.

Change the above to:

record = [output_humi, output_temp, output_pres]

You are also missing a { in your format specification. It should be:

sqlText = '''INSERT INTO data(humidity, temperature, pressure) VALUES({},{}, {})'''.format(values[0], values[1], values[2])

An alternative would be to use a prepared statement:

sqlText = 'INSERT INTO data(humidity, temperature, pressure) VALUES(%s, %s, %s)'
mycursor.execute(sqlText, values)

In the above case you will be passing actual strings as the values. I don't know how the columns are defined, but no matter. If they are defined as floating point or decimal values, the strings will be converted to the correct type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.