python执行许多"重复密钥更新"?

Jus*_*use 2 python mysql-python

我试图在重复密钥更新的python中执行manman,使用以下脚本:

# 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)
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

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
Run Code Online (Sandbox Code Playgroud)

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

unu*_*tbu 9

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

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

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

insert_values= re.compile(restr)
Run Code Online (Sandbox Code Playgroud)

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

也许这个bug是可以修复的,我真的不知道.但我认为这只是冰山一角 - 它指的是潜伏得更深一些的麻烦.例如,你可以INSERT ... SELECT使用SELECT带有WHERE条件和参数的嵌套语句的声明......使正则表达式越来越复杂以处理这些情况在我看来似乎是一场失败的战斗.

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


小智 5

当您编写如下 sql 时:

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

您将收到以下错误: 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)' 
Run Code Online (Sandbox Code Playgroud)