Python 基础教程

Python 高级教程

Python 相关应用

Python 笔记

Python FAQ

original icon
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.knowledgedict.com/tutorial/python-pymysql-execute-takes-from-2-to-3-positional-arguments-but-6-were-given.html

python pymsql execute 报错 TypeError: execute() takes from 2 to 3 positional arguments but 6 were given

Python 各类错误异常原因及相应解决方法 Python 各类错误异常原因及相应解决方法


python 中通过 pymysql 执行 execute 时,报错 TypeError: execute() takes from 2 to 3 positional arguments but 6 were given 的原因及解决方法?

错误信息

要通过 %s 作为占位符 sql 时,替换参数每个用一个参数位导致的,具体如下:

Traceback (most recent call last):
  File "op_mysql_once.py", line 75, in <module>
    op()
  File "op_mysql_once.py", line 63, in op
    cursor.execute(sql, tup[1], tup[0], tup[1], tup[0])
TypeError: execute() takes from 2 to 3 positional arguments but 6 were given

原因

不管 sql 中有多少个占位符,需要用一个集合类封装在一起,可以用元组或列表类型包在一起,且 execute 函数只接收 2 到 3 个参数,具体如下:

    def execute(self, query, args=None):
        """Execute a query

        :param str query: Query to execute.

        :param args: parameters used with query. (optional)
        :type args: tuple, list or dict

        :return: Number of affected rows
        :rtype: int

        If args is a list or tuple, %s can be used as a placeholder in the query.
        If args is a dict, %(name)s can be used as a placeholder in the query.
        """
        ...
        ...

解决方案

原因中道出了解决方法,将替换数据用元组(tuple)或列表(list)包在一起;或者用字典形式将占位符的名称与其 key 一一对应,如上 execute 函数说明中所述。

cursor.execute(sql, (tup[1], tup[0], tup[1], tup[0]))