mysql executemany与 insert ... ON DUPLICATE KEY UPDATE 一起使用

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


在将executemany()和“ON DUPLICATE KEY UPDATE”联合起来使用时需要注意一个小问题。
假设在数据库中有一个表A,其各个字段如下所示:
字段类型id (关键字)CHAR(8)last_dateDATEcountINT(11)
现在我们要想向表中批量插入数据:若关键字存在则更新last_date并将count累加。则sql应该如下书写:
# 省略imports和建立数据库连接的代码

# 省略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和建立数据库连接的代码

# 省略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.
————————————————
版权声明:本文为CSDN博主「yongyuandeie」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yongyuandeie/article/details/46381307

原文地址:https://www.cnblogs.com/lxfdf/p/14960587.html