python - 属性错误: 'tuple' object has no attribute 'encode' Arduino and MySQL

标签 python mysql arduino

我需要读取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

如何修复此错误?

最佳答案

您从代码中输入了错误的参数语法。试试这个:

 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

希望对您有帮助!

关于python - 属性错误: 'tuple' object has no attribute 'encode' Arduino and MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40697250/

相关文章:

python - Pandas:具有多种功能的分组和聚合

Python-位置参数跟随关键字参数

c# - 尝试创建 NHibernate 和 FluentNHibernate 来连接 MySQL?

PHP 函数在数据库中搜索值并在循环中替换

algorithm - 凯撒密码加密给出错误的输出

python - 我有一些代码,我想对其进行一些故障排除

python - 通过猴子修补 DEFAULT_PROTOCOL 提高 pickle.dumps 的性能?

php - 如何检查变量是否与 fetch() 具有相同的值

C++ 方法定义和变量声明

c++ - 在 Arduino 中除以两个整数