环境:ubuntu 14.04,MySQL 5.6,Python 2.7。
本文使用python的MySQLdb这个库,MySQL Python tutorial这个教程很赞。
MySQLDBdb处理INSERT、UPDATE、DELETE时需要显式得commit()才能使更新有效,这也意味着commit之前的更新语句是放在一个事务中的。
For databases that support transactions, the Python interface silently starts a transaction when the cursor is created. The commit() method commits the updates made using that cursor, and the rollback() method discards them. Each method starts a new transaction.
对比如下:
更新方式总时间(ms)rows平均(ms)
1
57831
1000
57.8
2
89695
10
896
3
92941
40×10000
0.23
4
47956
40×10000
0.119
5
28407
40×10000
0.071
6
3272
48×10000
0.008
方式1是单线程,where使用了索引,一个更新对应一个commit。
方式2是单线程,where没有使用索引,所有更新对应一个commit。
方式3是单线程,where使用了索引,所有更新对应一个commit。
方式4使用了2个进程来更新,where使用了索引,每个进程里的所有更新对应一个commit。
方式5使用了4个进程来更新,where使用了索引,每个进程里的所有更新对应一个commit。
方式6是在一个update语句里面更新所有的数据。
建立表
mysql> CREATE TABLE `test`.`number` (
`id` INT NOT NULL COMMENT '',
`num` INT NULL COMMENT '',
PRIMARY KEY (`id`) COMMENT '');
mysql> show create table number \G
*************************** 1. row ***************************
Table: number
Create Table: CREATE TABLE `number` (
`id` int(11) NOT NULL,
`num` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
使用mysqldb插入数据(100*000条)
# coding: UTF-8
__author__ = 'letian'
import MySQLdb
import time
host='127.0.0.1'
user='root'
passwd='123456'
db='test'
port = 3306
start_time = time.time()
conn = MySQLdb.connect(host, user, passwd, db, port)
cur = conn.cursor()
for x in xrange(100*10000): # 0 到 999999
print x
sql = "INSERT INTO number VALUES(%s,%s)" % (x, x)
cur.execute(sql)
conn.commit()
end_time = time.time()
print '用时:', end_time - start_time
运行结果:
...
999997
999998
999999
用时:219.332565069
挺快。
看下数据:
mysql> select count(*) from number;
+----------+
| count(*) |
+----------+
| 1000000 |
+----------+
1 row in set (0.60 sec)
mysql> select * from number limit 3;
+----+------+
| id | num |
+----+------+
| 0 | 0 |
| 1 | 1 |
| 2 | 2 |
+----+------+
3 rows in set (0.00 sec)
更新方式1:单线程,使用索引,多个co