【问题标题】:python execute many with "on duplicate key update"?python用“重复键更新”执行很多?
【发布时间】:2012-10-01 06:31:31
【问题描述】:

我正在尝试使用以下脚本在 python 中执行重复密钥更新:

# data from a previous query (returns 4 integers in each row)
rows = first_cursor.fetchall()

query="""
INSERT INTO data (a, b, c)
VALUES (%s,%s,%s) ON DUPLICATE KEY UPDATE a=%s
"""
second_cursor.executemany(query,rows)

我收到此错误:

File "/usr/lib/pymodules/python2.6/MySQLdb/cursors.py", line 212, in executemany
  self.errorhandler(self, TypeError, msg)
File "/usr/lib/pymodules/python2.6/MySQLdb/connections.py", line 35, in defaulterrorhandler
  raise errorclass, errorvalue
TypeError: not all arguments converted during string formatting

如果不创建我自己的循环,这是否可能?

【问题讨论】:

  • 当项目的数量与您应该填写的内容和您实际传递的内容不匹配时,会发生此错误。 >>> a = 1 >>> b = 2 >>> print "%s" % (a,b) Traceback(最近一次调用最后):文件“”,第 1 行,在 类型错误:在字符串格式化期间并非所有参数都转换 >>>

标签: python mysql-python


【解决方案1】:

由于 MySQLdb 使用正则表达式解析 INSERT 语句,这是 MySQLdb 中的一个错误:

/usr/lib/pymodules/python2.7/MySQLdb/cursors.py

restr = (r"\svalues\s*"
        r"(\(((?<!\\)'[^\)]*?\)[^\)]*(?<!\\)?'"
        r"|[^\(\)]|"
        r"(?:\([^\)]*\))"
        r")+\))")

insert_values= re.compile(restr)

虽然有很多关于这个问题的bug reports 已被解决,但我能够在 MySQLdb 版本 1.2.3 中重现该错误。 (注意此时MySQLdb的latest version是1.2.4b4。)

也许这个错误是可以修复的,我真的不知道。但我认为这只是冰山一角——它表明更多的麻烦潜伏在更深的地方。例如,您可以有一个 INSERT ... SELECT 语句,其中嵌套了 SELECT 语句,其中 WHERE 条件和参数散布在各处……在我看来,让正则表达式越来越复杂地处理这些情况似乎是一场失败的战斗。

你可以使用oursql;它不使用正则表达式或字符串格式。它将参数化查询和参数分别传递给服务器。

【讨论】:

    【解决方案2】:

    当你像下面这样写sql时:

    sql = insert into A (id, last_date, count) values(%s, %s, %s) on duplicate key update last_date=%s, count=count+%s'
    

    你会得到如下错误:TypeError: not all arguments converted during string formatting.

    所以当你在python中使用"ON DUPLICATE KEY UPDATE"时,需要这样写sql:

    sql = 'insert into A (id, last_date, count) values(%s, %s, %s) on duplicate key update last_date=values(last_date),count=count+values(count)' 
    

    【讨论】:

      【解决方案3】:

      找到:

      on duplicate key update col1=VALUES(col1), col2=VALUES(col2)
      

      https://hardforum.com/threads/python-mysql-not-all-arguments-converted-during-string-formatting.1367039/

      【讨论】:

        【解决方案4】:

        这是ubuntu说的mysqldb的一个bug,稍微改一下sql就可以了:

        insert into tb_name(col1, col2) select 1,2 on duplicate key update col1=1
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-17
          • 2017-03-19
          • 2019-07-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多