0

Basically, I am trying to send result from ultrasonic sensor to mysql db. I am able to send data I manually type into INSERT. however, I am not able to send the variable result.

This is the script for getting the number:

elapsed = stop - start    
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * speedSound

# That was the distance there and back so halve the value
distance = distance / 2
distance = '{:f}'.format(distance)
print(distance)

Result looks like 6.110798.

Then, I try to send it do DB:

# Open database connection
db = MySQLdb.connect("192.168.2.3","DB","**********","Ultrasonic_IoT" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = "INSERT INTO Pi (distance) VALUES (%distance)"

try:

    # Execute the SQL command
    cursor.execute(sql)
    # Commit your changes in the database
    db.commit()

except:
    # Rollback in case there is any error
    db.rollback()

    # disconnect from server
    db.close()

I tried different combinations in VALUE, however I am still stuck.

Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103

1 Answers1

0

Ok, so this did the trick

sql = "INSERT INTO UltraSonic (distance) VALUES (%s)"

try: # Execute the SQL command cursor.execute(sql, (distance))