一次插入多條數據時,可以使用 insert into table values (v1), (v2) ... (vn) 語句,這樣可以避免程序和數據庫建立多次連接,從而減少服務器運行時間。
實驗設計:
數據庫 | mysql |
數據庫地址 | 本機 |
數據總數 | 10萬 |
程序語言 | Python |
數據庫設計:
代碼:
#encoding=utf8
import pymysql
import string
import random
import time
def get_ran_str():
return ''.join(random.sample(string.ascii_letters + string.digits, 16))
def get_values_exp(count):
exp = []
for i in range(0, count):
name = get_ran_str()
key = get_ran_str()
value = get_ran_str()
exp.append(f"('{name}', '{key}', '{value}')")
return ",".join(exp)
if __name__ == '__main__':
conn = pymysql.connect('localhost', '', '', 'db')
cursor = conn.cursor()
arr_count = [1,2,5,10,20,50,100,200,500,1000,2000,5000,10000,20000,50000]
for count in arr_count:
sql = "delete from test_insert;"
cursor.execute(sql)
sql = 'alter table test_insert auto_increment=1;'
cursor.execute(sql)
conn.commit()
num = 100000
begin_time = time.time()
for i in range(0, num//count):
sql = "insert into test_insert(`name`,`key`,`value`) values " + get_values_exp(count)
cursor.execute(sql)
conn.commit()
end_time = time.time()
run_time = end_time - begin_time
print(f'每塊{count}條數據的運行時間:{run_time}秒')
實驗結果:
每塊數據條數 | 運行時間 |
1 | 625.0080001354218 |
2 | 324.8550000190735 |
5 | 146.0849997997284 |
10 | 85.9079999923706 |
20 | 53.58800005912781 |
50 | 32.60899996757507 |
100 | 25.304999828338623 |
200 | 21.836999893188477 |
500 | 17.63699984550476 |
1000 | 11.73800015449524 |
2000 | 14.864000082015991 |
5000 | 14.25499963760376 |
10000 | 11.13699984550476 |
20000 | 10.92199969291687 |
50000 | 10.728999853134155 |
100000 | 異常 |
實驗分析:
運行時間隨塊大小的增大先急劇減少,然後趨於穩定
數據分塊大小不能無限大,當塊大小爲10萬時,程序就會拋出異常:
使用事務進行插入處理能夠數據插入效率:
for i in range(0, num//count):
sql = "insert into test_insert(`name`,`key`,`value`) values " + get_values_exp(count)
cursor.execute(sql)
conn.commit()
實驗結果如下:
每塊數據條數 | 運行時間 |
1 | 28.40499997138977 |
2 | 14.674999713897705 |
5 | 10.174000263214111 |
10 | 8.79200005531311 |
20 | 8.255000114440918 |
50 | 7.776000022888184 |
100 | 7.33899998664856 |
200 | 7.374999761581421 |
500 | 7.142000198364258 |
1000 | 7.124000072479248 |
2000 | 7.20799994468689 |
5000 | 7.055999994277954 |
10000 | 7.039999961853027 |
20000 | 7.091000080108643 |
50000 | 7.04800009727478 |
實驗分析:
運行時間隨塊大小的增大先急劇減少,然後趨於穩定,最後穩定在7s左右
總結:
提示批量插入性能的方法:
1、使用事務管理
2、使用 insert into table values (v1), (v2) ... (vn) 分塊批量插入,塊大小不宜過小,也不宜過大