简体   繁体   English

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

[英]Can't insert in a table or create a table in MySQL using Python

I have a arduino uno and temp36. 我有一个arduino uno和temp36。 I read the sensor value from the arduino serial Monitor with Python. 我从使用Python的arduino串行监视器读取传感器值。 It works!! 有用!!

But I can't insert in a created MySQL Table using Python and I don't know why. 但是我无法使用Python在创建的MySQL表中插入,我不知道为什么。 I have no error or warning. 我没有错误或警告。

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

Am I doing something wrong? 难道我做错了什么?

Those Value in SQL-table need to be plot in php (real time ploting) SQL表中的那些值需要在php中绘图(实时绘图)

Hardware: windows 7, Python 2.7, Python editor:Pyscripter, arduino uno, MySQL Workbench 硬件:Windows 7,Python 2.7,Python编辑器:Pyscripter,arduino uno,MySQL Workbench

You have to commit after executing the sql statement: 执行sql语句后必须提交:

cursor.execute(sql)
cursor.commit()

or set autocommit=True after the connection is established. 建立连接后设置autocommit=True

If you open database connection it is initially with autocommit=False mode, so after you execute SQL statement you must commit() it. 如果打开数据库连接,它最初使用autocommit=False模式,因此在执行SQL语句后必须commit()它。 Also do not pass on exception. 也不要pass异常。 This way you will not see problems. 这样你就不会看到问题了。 You can log exception into file. 您可以将异常记录到文件中。 You also use cursor.rowcount before you execute INSERT statement. 在执行INSERT语句之前,还要使用cursor.rowcount Use it after it. 之后使用它。

From your comments it seems that you do not defined arduino_temp database. 从您的评论看来,您似乎没有定义arduino_temp数据库。 I do not have MySQL database but I have tested such code with PostgreSQL and ODBC driver. 我没有MySQL数据库,但我已经使用PostgreSQL和ODBC驱动程序测试了这样的代码。 You can use it to test your database and driver: 您可以使用它来测试数据库和驱动程序:

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

If you have problem with database create test code and use small functions. 如果您在使用数据库创建测试代码和使用小函数时遇到问题。 Your code is mixed reading temperature from serial interface and inserting it into database. 您的代码是串行接口的混合读取温度并将其插入数据库。 Make separate functions for each operation. 为每个操作创建单独的功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM