我的MySQL表架構是:與只做一個'IN'查詢相比,爲什麼'executemany'這麼慢?
CREATE DATABASE test_db;
USE test_db;
CREATE TABLE test_table (
id INT AUTO_INCREMENT,
last_modified DATETIME NOT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB;
當我運行下面的基準腳本,我得到:
B1:20.5559301376
B2:0.504406929016
from timeit import timeit
import MySQLdb
ids = range(1000)
query_1 = "update test_table set last_modified=UTC_TIMESTAMP() where id=%(id)s"
query_2 = "update test_table set last_modified=UTC_TIMESTAMP() where id in (%s)" % ", ".join(('%s',) * len(ids))
db = MySQLdb.connect(host="localhost", user="some_user", passwd="some_pwd", db="test_db")
def b1():
curs = db.cursor()
curs.executemany(query_1, ids)
db.close()
def b2():
curs = db.cursor()
curs.execute(query_2, ids)
db.close()
print "b1: %s" % str(timeit(lambda:b1(), number=30))
print "b2: %s" % str(timeit(lambda:b2(), number=30))
01爲什麼會有這麼大的差異?和IN
子句?
我使用Python 2.6.6和MySQL-python 1.2.3。
我能找到的唯一相關問題是 - Why is executemany slow in Python MySQLdb?,但這並不是我真正想要的。
關鍵的區別是'executemany'不能保證單個數據庫往返。這是'盡最大努力',其中努力往往不是很大,而'實際單一語句往返'卻不是那麼好。另請參閱https://stackoverflow.com/questions/4101076/executemany-confusion – pvg