MySQLdb(Python)executemany和ON DUPLICATE KEY UPDATE的使用问题
2015-06-05 20:18
721 查看
在将executemany()和“ON DUPLICATE KEY UPDATE”联合起来使用时需要注意一个小问题。
假设在数据库中有一个表A,其各个字段如下所示:
现在我们要想向表中批量插入数据:若关键字存在则更新last_date并将count累加。则sql应该如下书写:
注意这里的sql变量不能按照常规模式书写,即:
否则会报如下错误:
TypeError: not all arguments converted during string formatting.
假设在数据库中有一个表A,其各个字段如下所示:
字段 | 类型 |
---|---|
id (关键字) | CHAR(8) |
last_date | DATE |
count | INT(11) |
# 省略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动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法
- Python实现的基于ADB的Android远程工具