我正在尝试通过Python将Arduino数据插入数据库中,但是不会这样做。基本上,我分配的是从分配给Arduino的串行端口读取的数据,并将其第一个值存储在变量arduinoData中。在我的插入语句中,我试图使用字符串文字将arduinoData放入表中。这是代码:

import mysql.connector
from mysql.connector import errorcode
from time import sleep
import serial

# Obtain connection string information from the portal
config = {
  'host':'oursystem.mysql.database.azure.com',
  'user':'project',
  'password':'',
  'database':'projectdb'
}

# Construct connection string
try:
   conn = mysql.connector.connect(**config)
   print("Connection established")
except mysql.connector.Error as err:
  if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
    print("Something is wrong with the user name or password")
  elif err.errno == errorcode.ER_BAD_DB_ERROR:
    print("Database does not exist")
  else:
    print(err)
else:
  cursor = conn.cursor()
  ser = serial.Serial('/dev/ttyACM0', 9600) # Establish the connection on a specific port
  arduinoData=ser.read().strip()
  print arduinoData
  # Drop previous table of same name if one exists
  cursor.execute("DROP TABLE IF EXISTS ArduinoData;")
  print("Finished dropping table (if existed).")

  # Create table
  cursor.execute("CREATE TABLE ArduinoData (value VARCHAR(20));")
  print("Finished creating table.")

  # Insert some data into table
  cursor.execute("INSERT INTO ArduinoData (value) VALUES (%s);",(arduinoData))
  print("Inserted",cursor.rowcount,"row(s) of data.")


  # Cleanup
  conn.commit()
  cursor.close()
  conn.close()
  print("Done.")


如果我将%s用单引号引起来,例如'%s',它将仅打印该内容而不是我的arduinoData。任何人都可以看到这里出了什么问题,谢谢。

最佳答案

只需传递一个元组(arduinoData,),这意味着参数化中单个值或列表[arduinoData]而不是单个值(arduinoData)括号内的逗号:

cursor.execute("INSERT INTO ArduinoData (`value`) VALUES (%s);",(arduinoData,))


但是,如果arduinoData是多个值的列表,则使用executemany,仍会传递一个列表。另外,转义value这是MySQL reserved word

cursor.executemany("INSERT INTO ArduinoData (`value`) VALUES (%s);",[arduinoData])

10-06 01:46