【发布时间】:2014-06-06 13:52:49
【问题描述】:
我有一个 arduino uno 和 temp36。我用 Python 从 arduino 串行监视器读取传感器值。有用!!
但我无法使用 Python 在创建的 MySQL 表中插入,我不知道为什么。我没有错误或警告。
import serial
import time
import MySQLdb
dbhost = 'localhost'
dbname = 'test'
dbuser = 'X'
dbpass = 'Y'
ser = serial.Serial('COM7',9600,timeout=1) # On Ubuntu systems, /dev/ttyACM0 is the default path to the serial device on Arduinos, yours is likely different.
while 1:
time.sleep(1)
the_goods = ser.readline()
str_parts = the_goods.split(' ')
conn = MySQLdb.connect (host = dbhost,
user = dbuser,
passwd = dbpass,
db = dbname)
cursor = conn.cursor ()
sql = "INSERT INTO arduino_temp (temperature) VALUES ('%s');" % (str_parts[0])
print "Number of rows inserted: %d" % cursor.rowcount
try:
cursor.execute(sql)
except:
pass
cursor.close ()
conn.autocommit=True
conn.close ()
print the_goods
我做错了吗?
SQL 表中的值需要在 php 中绘制(实时绘制)
硬件:windows 7、Python 2.7、Python 编辑器:Pyscripter、arduino uno、MySQL Workbench
【问题讨论】:
-
您需要从删除
try/except总括异常处理开始。您的autocommit更改来得太晚,无法应用于插入语句。 -
您不应该对 sql 命令进行字符串格式化,而是使用占位符:
cursor.execute('INSERT INTO arduino_temp (temperature) VALUES (%s)', str_parts[0]) -
非常感谢您的回复。我收到一个错误:编程错误:“表 test.arduino_temp 不存在。”该错误是什么意思?