[英]insert to mysql variable from python script
基本上,我試圖將結果從超聲波傳感器發送到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。
然后,我嘗試將其發送給數據庫:
# 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中嘗試了不同的組合,但是仍然遇到問題。
好的,這就是竅門
sql = "INSERT INTO UltraSonic (distance) VALUES (%s)"
嘗試:#執行SQL命令cursor.execute(sql,(distance))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.