我们测试下3种插入操作方式的性能情况(以10000次为例):
# coding:utf-8 import time import pymysql from settings import * con = pymysql.Connect(host=MYSQL_HOST, username=MYSQL_USER, password=MYSQL_PASSWORD, port=MYSQL_PORT, database=MYSQL_DATABASE) cur = con.cursor() sql = 'insert into test_table(test_field) values(%s);' # 1、执行和提交10000次 def test1(): t1 = time.time() for i in range(10000): try: cur.execute(sql,[i]) con.commit() except Exception as e: print(e) con.rollback() t2 = time.time() print('使用10000次execute和commit耗时:%.2f秒'%(t2-t1)) # 2、执行10000次,提交1次 def test2(): t1 = time.time() try: for i in range(10000): cur.execute(sql,[i]) con.commit() except Exception as e: print(e) con.rollback() t2 = time.time() print('使用execute执行10000次,commit1次耗时:%.2f秒'%(t2-t1)) # 3、执行executemany1次,提交1次 def test3(): t1 = time.time() args_list = [] for i in range(10000): args_list.append(i) try: cur.executemany(sql,args_list) con.commit() except Exception as e: print(e) con.rollback() t2 = time.time() print('使用executemany执行1次,commit1次耗时:%.2f秒'%(t2-t1)) def main(): test1() test2() test3() if __name__ == '__main__': main()
使用10000次execute和commit耗时:12.96秒 使用execute执行10000次,commit1次耗时:0.94秒 使用executemany执行1次,commit1次耗时:0.05秒
很明显,1次缓冲多条命令,效率会高于分次提交,同时executemany方法会进一步提升效率