我有一个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
答案 0 :(得分:1)
执行sql语句后必须提交:
cursor.execute(sql)
cursor.commit()
建立连接后或设置autocommit=True
。
答案 1 :(得分:1)
如果打开数据库连接,它最初采用autocommit=False
模式,因此在执行SQL语句后,您必须commit()
它。在例外情况下也不要pass
。这样你就不会看到问题了。您可以将异常记录到文件中。在执行INSERT语句之前,还要使用cursor.rowcount
。在它之后使用它。
您的评论似乎没有定义arduino_temp
数据库。我没有MySQL数据库,但我已经使用PostgreSQL和ODBC驱动程序测试了这样的代码。您可以使用它来测试数据库和驱动程序:
import MySQLdb
import traceback
def ensure_table(conn):
cursor = conn.cursor()
try:
cursor.execute('SELECT COUNT(*) FROM arduino_temp')
for txt in cursor.fetchall():
print('Number of already inserted temepratures: %s' % (txt[0]))
except:
s = traceback.format_exc()
print('Problem while counting records:\n%s\n' % (s))
print('Creating arduino_temp table ...')
# table arduino_temp does not exist
# you have to define table there
# you will probably have to add some columns as:
# test_id SERIAL primary key,
# test_date timestamp default CURRENT_TIMESTAMP,
# and add index on test_date
cursor.execute('CREATE TABLE arduino_temp (temperature integer)')
print('table created')
cursor.close()
def insert_temperature(conn, temperature):
cursor = conn.cursor()
#cursor.execute("INSERT INTO arduino_temp (temperature) VALUES (?)", (temperature, ))
#cursor.execute("INSERT INTO arduino_temp (temperature) VALUES (%s)", (temperature, ))
cursor.execute("INSERT INTO arduino_temp (temperature) VALUES (%d)" % (int(temperature)))
print("Number of rows inserted: %d" % (cursor.rowcount))
conn.commit()
cursor.close()
def main():
# ...
conn = MySQLdb.connect (host = dbhost, user = dbuser, passwd = dbpass, db = dbname)
#conn = pyodbc.connect('DSN=isof_test;uid=dbuser;pwd=dbpass')
ensure_table(conn)
insert_temperature(conn, 10)
main()
如果您在使用数据库创建测试代码时遇到问题并使用小功能。您的代码是串行接口的混合读取温度并将其插入数据库。为每个操作分别创建功能。