2016-12-03 110 views
0

基本上,我试图将结果从超声波传感器发送到mysql数据库。我能够将数据手动输入到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() 

我VALUE尝试不同的组合,但我仍然坚持。

+0

尝试'SQL =“INSERT INTO PI(距离)VALUES%s“%距离” – MYGz

+0

阅读更多关于字符串替换:http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format/6335836#6335836 – MYGz

+0

仍然不工作 - 试图改变%s到%d - ValueError:不完整的格式....是字符串正确的格式,当我的数据库期望在行中十进制? –

回答

0

好了,所以这并获得成功

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

尝试: #执行SQL命令 cursor.execute(SQL,(距离))