【发布时间】:2017-10-26 20:22:41
【问题描述】:
我的 MySQL 表架构是:
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))
为什么executemany和IN子句有这么大的区别?
我正在使用 Python 2.6.6 和 MySQL-python 1.2.3。
我能找到的唯一相关问题是 - Why is executemany slow in Python MySQLdb?,但这并不是我真正想要的。
【问题讨论】:
-
主要区别在于
executemany不保证单个数据库往返。这是“尽力而为”的努力,与“实际的单语句往返”相比,努力通常不是那么好。另见stackoverflow.com/questions/4101076/executemany-confusion
标签: python mysql performance mysql-python