您的位置:首页 > 编程语言 > Python开发

MySQLdb(Python)executemany和ON DUPLICATE KEY UPDATE的使用问题

2015-06-05 20:18 721 查看
在将executemany()和“ON DUPLICATE KEY UPDATE”联合起来使用时需要注意一个小问题。

假设在数据库中有一个表A,其各个字段如下所示:

字段类型
id (关键字)CHAR(8)
last_dateDATE
countINT(11)
现在我们要想向表中批量插入数据:若关键字存在则更新last_date并将count累加。则sql应该如下书写:

# 省略imports和建立数据库连接的代码
data_items = [['1', '2015-06-05', 10], ['2', '2015-06-05', 20], ...]

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)'

try:
with closing(connection.cursor()) as cursor:
cursor.executemany(sql, info_tuple)
connection.commit()
except MySQLdb.Error, e:
print("Mysql Error %d: %s" % (e.args[0], e.args[1]))


注意这里的sql变量不能按照常规模式书写,即:

# 省略imports和建立数据库连接的代码
data_items = [['1', '2015-06-05', 10, '2015-06-05', 10],
['2', '2015-06-05', 20, '2015-06-05', 20], ...]

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 MySQLdb