mysql.connector.errors.ProgrammingError:处理格式参数失败; Python'tuple'无法转换为MySQL类型

时间:2016-11-18 02:22:47

标签: python mysql

我是Python的新手,我找不到足够的这种模式的例子。运行Python 3.4,安装了MySQL Python Connector。 MySQL版本5.7。

使用这组代码(我用空格替换了用户,密码等的值):

import mysql.connector
cnx = mysql.connector.connect(user='', 
                        password='   ',
                        host='    ',
                        database='     ')
cursor = cnx.cursor()  
PortExistsQ = "SELECT Count(*) FROM portfolio WHERE idPortfolio=%s AND YearWeek(Signal_Date)=%s AND Rank=1"
cursor.execute(PortExistsQ,(portID,Yearweek))

我收到此错误。

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\mysql\connector\conversion.py", line 179, in to_mysql
    return getattr(self, "_{0}_to_mysql".format(type_name))(value)
AttributeError: 'MySQLConverter' object has no attribute '_tuple_to_mysql'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 417, in _process_params
    res = [to_mysql(i) for i in res]
  File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 417, in <listcomp>
    res = [to_mysql(i) for i in res]
  File "C:\Python34\lib\site-packages\mysql\connector\conversion.py", line 182, in to_mysql
    "MySQL type".format(type_name))
TypeError: Python 'tuple' cannot be converted to a MySQL type

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python34\lib\threading.py", line 920, in _bootstrap_inner
    self.run()
  File "C:\Python34\lib\threading.py", line 868, in run
    self._target(*self._args, **self._kwargs)
  File "C:\workspace\DIY Investing\CSI\CalcP.py", line 56, in calcport
    cursor.execute(PortExistsQ,(portID,Yearweek))
  File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 539, in execute
    psub = _ParamSubstitutor(self._process_params(params))
  File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line 422, in _process_params
    "Failed processing format-parameters; %s" % err)
mysql.connector.errors.ProgrammingError: Failed processing format-parameters; Python 'tuple' cannot be converted to a MySQL type

SQL在MySQL Workbench中按预期运行。对于Portfolio of 2和YearWeek of 201644(导致错误的第一个值),MySQL中的结果是Count(*)为1.

的代码段
print ("Portfolio", portID, "YearWeek", Yearweek)

生成以下输出

Portfolio 2 YearWeek (201644,)

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

该错误表示元组无法转换为mysql类型,当您执行print语句时,它变得相当明显

print ("Portfolio", portID, "YearWeek", Yearweek)
Produces the following output

Portfolio 2 YearWeek (201644,)

Yearweek是一个元组使用Yearweek [0]而不是

答案 1 :(得分:1)

根据您的示例 - Yearweek是一个元组(201644,),您不能将元组用作预准备语句的值。

您可以改用:

cursor.execute(PortExistsQ,(portID,Yearweek[0]))

或者

Yearweek = Yearweek[0]
cursor.execute(PortExistsQ,(portID,Yearweek))

这样,传递给execute函数的值是201644(这是元组中的第一个值),而不是元组本身。