摘要:
1自动化单条insert => 单条insert的话插入5w条数据大约用时5秒左右,相对来说效率不高
2拼接sql语句,只执行一次insert =>使用这种批量插入方式插入5w条数据用时大约不到1秒
1.自动化单条insert
# -*- coding:utf-8 -*- import time from pymysql import * # 装饰器,计算插入50000条数据需要的时间 def timer(func): def decor(*args): start_time = time.time() func(*args) end_time = time.time() d_time = end_time - start_time print("the "+str(func.__name__)+" running time is : ", d_time) return decor @timer def add_test_users(): conn = connect(host='127.0.0.1', port='3306', user='root', password='root', database='数据库名', charset='utf8') cs = conn.cursor() # 获取游标 for num in range(0, 50000): try: sql = "insert into '表名'(字段名) values(值)" cs.execute(sql) except Exception as e: return conn.commit() # 提交 cs.close() conn.close() print('OK') add_test_users()
单条insert的话插入5w条数据大约用时5秒左右,相对来说效率不高
2.拼接sql语句,只执行一次insert
# -*- coding:utf-8 -*- import time from pymysql import * # 装饰器,计算插入50000条数据需要的时间 def timer(func): def decor(*args): start_time = time.time() func(*args) end_time = time.time() d_time = end_time - start_time print("the running time is : ", d_time) return decor @timer def add_test_users(): usersvalues = [] for num in range(1, 50000): usersvalues.append(('zhangsan','23')) # 注意要用两个括号扩起来 conn = connect(host='127.0.0.1', port='3306', user='root', password='root', database='数据库名', charset='utf8') cs = conn.cursor() # 获取光标 # 注意这里使用的是executemany而不是execute,下边有对executemany的详细说明 cs.executemany('insert into '表名'(name,age) values(%s,%s)', usersvalues) conn.commit() cs.close() conn.close() print('OK') add_test_users()
原文: https://blog.csdn.net/weixin_42703149/article/details/85120029