我需要通过串口读取Arduino发送的一些数字,然后将这些数字插入MySQL表中。
这是我的代码:
import mysql.connector, serial
ser = serial.Serial(port='/dev/ttyACM3', baudrate='9600')
ser.isOpen()
read_port = ser.readline()
print (read_port)
mysql_connection = mysql.connector.connect(host="localhost", user="optim_admin", passwd="marcopolo", database="optimbit_acces")
cursor = mysql_connection.cursor()
sql1 = "insert into check_in (card, checkin) values (%s, Now()); ", (read_port)
cursor.execute(sql1)
mysql_connection.close()
这是我的错误:
Traceback (most recent call last):
File "/home/admin1/Documents/OptimAcces/db_service_connect.py", line 10, in <module>
cursor.execute(sql1, (str(read_port.decode('unicode_escape').encode('ascii', 'utf-8')), ))
File "/usr/local/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 492, in execute
stmt = operation.encode(self._connection.python_charset)
AttributeError: 'tuple' object has no attribute 'encode'
Process finished with exit code 1
如何解决此错误?
答案 0 :(得分:0)
您正在从代码中输入错误的参数语法。试试这个:
from time import gmtime, strftime
date_time = strftime("%Y-%m-%d %H:%M:%S", gmtime())
sql1 = "insert into check_in (card, checkin) values (%s, %s)"
args = read_port, date_time
cursor.execute(sql1, args)
您面临的错误消息是因为您的查询参数数量错误且更多括号未正确关闭。
请参阅下面的cursor.execute签名:
Definition: cursor.execute(self, query, args=None)
query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query
希望它有所帮助!
答案 1 :(得分:0)
感谢所有人。我通过从MySql切换数据库到MariaDb解决了这个问题。现在它工作正常。
感谢您的帮助。