mysql插入大量資料,時間的優化。

2021-08-16 13:16:48 字數 1344 閱讀 7589

背景:

業務場景假設,公司原有excel記錄了千萬級客戶的相關資料,公司業務結構實現了資訊化的布局,需要在新開發的crm系統中匯入千萬級的客戶資料。此時需要用到mysql的insert操作來插入使用者的海量資料。

普通情況下,會使用for迴圈一條一條的插入資料。

假設客戶的資料量為10萬條資料。

<?php 

$connect=@mysql_connect("localhost","root","") or die(mysql_error());

@mysql_select_db("test") or die(mysql_error());

@mysql_query("set names utf-8");

$start_time=microtime(true);

/* * 方法一,迴圈插入mysql資料

*/$sql="insert into test_table(value) values('1')";

for($i=0;$i<100000;$i++)

$end_time=microtime(true);

echo "程式的執行時間為:".($end_time-$start_time);

由上圖可見,程式執行速度非常慢,嚴重影響使用者體驗。

優化,對客戶的插入資料進行優化。

速度優化的核心法則,使用"insert into table value(value1,value2.......)";

既使用一條sql語句,對資料進行插入處理。

$connect=@mysql_connect("localhost","root","") or die(mysql_error());

@mysql_select_db("test") or die(mysql_error());

@mysql_query("set names utf-8");

$start_time=microtime(true);

/* * 方法二,拼接插入mysql資料

*/$sql="insert into test_table(value) values";

for($i=0;$i<100000;$i++)

$sql=substr($sql,0,strlen($sql)-1);

@mysql_query($sql) or die(mysql_error());

$end_time=microtime(true);

echo "程式的執行時間為:".($end_time-$start_time);

由上圖可見,同樣的10萬級的資料插入,速度已經從15s優化到了0.5s。  

mysql 儲存過程 插入大量資料

需求 測試sql語句的效能,在資料庫中插入10萬條資料用於測試。delimiter drop procedure if exists kxc create procedure kxc begin declare i int set i 0 start transaction while i 1000...

mysql迴圈插入大量測試資料

最近業務場景的需要,mysql單錶要插入大量資料,考慮到單條記錄長短對資料儲存量有很大的影響,所以進行了一次插入檢索測試。插入 procedure delimiter drop procedure if exists insert current data uuid create procedure...

Android SQLite插入大量資料的效率優化

通常,在用 arraylist contentprovideroperation operations new arraylist contentprovideroperation do something.operations add contentprovideroperation newupd...