【问题标题】:Can't insert in a table or create a table in MySQL using Python无法使用 Python 在 MySQL 中插入表或创建表
【发布时间】: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 不存在。”该错误是什么意思?

标签: php python mysql


【解决方案1】:

执行完sql语句后必须commit:

cursor.execute(sql)
cursor.commit()

或在建立连接后设置autocommit=True

【讨论】:

  • OP 确实尝试设置autocommit=True,但为时已晚。
【解决方案2】:

如果你打开数据库连接最初是autocommit=False模式,所以在你执行SQL语句后你必须commit()它。也不要在异常时pass。这样你就不会看到问题。您可以将异常记录到文件中。在执行 INSERT 语句之前,您还可以使用 cursor.rowcount。在它之后使用它。

从您的 cmets 看来,您似乎没有定义 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()

如果您对数据库有问题,请创建测试代码并使用小函数。您的代码混合从串行接口读取温度并将其插入数据库。为每个操作创建单独的函数。

【讨论】:

  • 非常感谢您的回复。我收到一个错误:programmingerror:" Table test.arduino_temp does not exist." 这个错误是什么意思?
  • 表示test数据库中没有arduino_temp表。您连接到错误的数据库或拼写错误的表名,或者您必须创建 arduino_temp 表。
  • 非常感谢您的回答。但它不起作用。
  • 如果您对数据库有问题,请创建测试代码并使用小功能。您的代码混合从串行接口读取温度并将其插入数据库。为每个操作创建单独的函数。向我们显示错误信息。确保arduino_temp 表在数据库中。
  • 嗨,我决定在 phpmyadmin 中创建一个新表。但只有第一个数据从 phpMyadmin 写入 MysqlTable。我不知道为什么。它不适用于 Workbench。我在 python 或 mysql 中没有错误。
猜你喜欢
  • 2019-03-20
  • 1970-01-01
  • 2015-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多