无法在MySQL中使用Python插入或创建表

0 投票
2 回答
1914 浏览
提问于 2025-04-18 03:43

我有一个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

2 个回答

1

当你打开数据库连接时,默认是autocommit=False模式,这意味着在你执行SQL语句后,必须手动调用commit()来保存更改。同时,不要在出现错误时直接跳过,这样你可能会错过一些问题。你可以把错误记录到文件里。还有,在执行插入(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()

如果你在数据库方面遇到问题,可以先创建一些测试代码,并使用简单的函数。你的代码现在把从串口读取温度和插入数据库的操作混在一起了。建议为每个操作单独写函数。

1

在执行完SQL语句后,你需要进行提交:

cursor.execute(sql)
cursor.commit()

或者在建立连接后,把autocommit=True设置为真。

撰写回答