【问题标题】:Does MySQLdb Cursors not support empty iterator?MySQLdb 游标不支持空迭代器吗?
【发布时间】:2013-11-10 02:45:02
【问题描述】:
cur.executemany(sql, rows)

我有 rows 作为空迭代器,它会触发错误。

如果我这样做cur.executemany(sql, list(rows)),那么它工作正常。

 File "/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/MySQLdb/cursors.py", line 252, in executemany
    r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]]))
  File "/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/MySQLdb/cursors.py", line 344, in _query
    rowcount = self._do_query(q)
  File "/Enthought/Canopy_64bit/User/lib/python2.7/site-packages/MySQLdb/cursors.py", line 308, in _do_query
    db.query(q)
_mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1")

以下是MySQLdb Cursors.py的代码

    def executemany(self, query, args):

        """Execute a multi-row query.

        query -- string, query to execute on server

        args

            Sequence of sequences or mappings, parameters to use with
            query.

        Returns long integer rows affected, if any.

        This method improves performance on multiple-row INSERT and
        REPLACE. Otherwise it is equivalent to looping over args with
        execute().

        """
        del self.messages[:]
        db = self._get_db()
        if not args: return
        if isinstance(query, unicode):
            query = query.encode(db.unicode_literal.charset)
        m = insert_values.search(query)
        if not m:
            r = 0
            for a in args:
                r = r + self.execute(query, a)
            return r
        p = m.start(1)
        e = m.end(1)
        qv = m.group(1)
        try:
            q = [ qv % db.literal(a) for a in args ]
        except TypeError, msg:
            if msg.args[0] in ("not enough arguments for format string",
                               "not all arguments converted"):
                self.errorhandler(self, ProgrammingError, msg.args[0])
            else:
                self.errorhandler(self, TypeError, msg)
        except (SystemExit, KeyboardInterrupt):
            raise
        except:
            exc, value, tb = sys.exc_info()
            del tb
            self.errorhandler(self, exc, value)
        r = self._query('\n'.join([query[:p], ',\n'.join(q), query[e:]]))
        if not self._defer_warnings: self._warning_check()
        return r

【问题讨论】:

    标签: python mysql mysql-python executemany


    【解决方案1】:

    简短的回答是:不,MySQLdb 不支持将空迭代器参数传递给executemany

    为什么不呢?因为if not args: return这行。这可以通过完全切断服务器并返回None 来处理不提供参数的情况。空列表、字典、集合或元组的真值是False,但迭代器的真值总是True

    如果您在cursors.py 中注释掉该行,那么任何空序列或映射都会抛出与空迭代器相同的ER_PARSE_ERROR

    为了让executemany 支持空参数,它必须以某种方式测试args 是否为空。如果args是一个迭代器,唯一的办法就是调用.next(),观察结果是否是StopIteration异常;没有其他方法可以确定任意迭代器是否为空。这是不切实际的,因为它使用迭代器中的项目并且不适用于任何非迭代器类型,而且毫无意义,因为 executemany 首先不打算在没有参数的情况下使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2021-08-12
      • 1970-01-01
      相关资源
      最近更新 更多