基本上,我试图将超声波传感器的结果发送到mysql db。我能够将手动输入的数据发送到INSERT中。但是,我无法发送变量结果。
这是获取号码的脚本:
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)
结果看起来像6.110798。
然后,我尝试发送它做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()
我在VALUE中尝试了不同的组合,但我仍然卡住了。
答案 0 :(得分:0)
好的,这就是诀窍
sql = "INSERT INTO UltraSonic (distance) VALUES (%s)"
尝试: #执行SQL命令 cursor.execute(sql,(distance))