2016-12-03 7 views
0

基本的に、私は超音波センサーからの結果をmysql dbに送信しようとしています。手動で入力するデータをINSERTに送信できます。しかし、私は変数の結果を送信することができません。pythonスクリプトからmysql変数に挿入

これは数を取得するためのスクリプトです:

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() 

私は価値の異なる組み合わせを試してみましたが、しかし、私はまだ立ち往生しています。

+0

を試し 'のsql =「INSERT INTOパイ(距離)VALUES%s "%distance" – MYGz

+0

文字列の置換についてもっと読む:http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format/6335836#6335836 – MYGz

+0

まだ動作していません - %sを変更しようとしました%dに - ValueError:不完全な書式....私のDBが行に期待しているときに文字列の正しい形式ですか? –

答えて

0

[OK]を、ので、これはトリック

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

試しました: #はSQLコマンド cursor.execute(SQL、(距離))を実行し

関連する問題