6

我正在尝试使用以下脚本在 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

如果不创建我自己的循环,这甚至可能吗?

4

4 回答 4

11

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

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

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

insert_values= re.compile(restr)

尽管有很多关于这个问题的错误报告已经被关闭,但我能够在 MySQLdb 版本 1.2.3 中重现该错误。(注意目前 MySQLdb 的最新版本是 1.2.4b4。)

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

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

于 2012-10-10T18:02:22.770 回答
6

当您编写如下 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.

所以"ON DUPLICATE KEY UPDATE"在python中使用的时候,需要这样写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)' 
于 2018-05-25T09:24:50.923 回答
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/

于 2018-01-13T05:26:55.263 回答
0

正如ubuntu所说,这是mysqldb的一个错误,只需更改sql即可:

insert into tb_name(col1, col2) select 1,2 on duplicate key update col1=1
于 2015-06-05T03:19:52.883 回答