关于executemany()方法在不同OS和DB API下的不同表现的测试

昨天在参照着网上写一段关于MySQL连接池的配合gevent多线程调用的代码时遇到了一个问题,自己写的代码根本不能多线程执行,比单会话插入数据慢太多,直到今天早上才发现问题所在,把DB API从MySQLdb换为pymysql之后得到解决,因此测试了一下不同DB API和OS下executemany()的表现,先贴一下剪短的测试代码:

# -*- coding: utf-8 -*-
import MySQLdb
import pymysql
import time
conn=pymysql.connect(host='192.168.1.174',port=3306,user='leo',passwd='leo',db='leo',charset='utf8')
conn.autocommit(True)
start_time=time.time()
with conn as cursor:
    data=((i,"Messi%s"%i) for i in range(10000))
    cursor.executemany("Insert into test values(%s,%s);",data)
    cursor.execute("select count(*) from test;")
    print(cursor.fetchall())
print("Elapsed Time: ",(time.time()-start_time))

以上一段代码在Python2、3通用,通过开启general log来观察SQL和事务状态。

使用不同版本的解释器执行测试的结果如下:

其他db api诸如sqlalchemy等未进行测试。

其实之前忘了在哪里也看到过在python3中mysqlclient、MySQLdb之间的关系,但是如此混乱的版本表现确实很恶心。

此外,在Python2中如果将executemany()封装入连接池类中,表现又有所不同,多条sql会在同一个会话中分为多个事务依次执行。

总结起来暂时就一句话:尽量使用python3的MySQLdb module。

原文地址:https://www.cnblogs.com/leohahah/p/10250540.html