MySQL MySQL快速插入大量資料

2021-08-15 02:34:39 字數 3083 閱讀 6057

目錄

在公司優化sql遇到乙個索引的問題,晚上回家想繼續驗證,無奈沒有較多資料的表,於是,想造一些隨機的資料,用於驗證。

於是動手寫。由於自己不是mysql能手,寫得也不好。最後,插入的速度也不快,我使用的是mysql的innodb引擎,電腦跑了差不多一通宵才插入100w資料(為自己的程式汗顏)。雖然這樣,我還是再次保留這份**,以防下次要使用。嘿嘿。(插入時切換成myisam引擎,插入速度會快很多,插入完畢再切換回來)

需要插入資料的表:

create

table

`t_member` (

`id`

int (11

), `member_no`

varchar (36

), `user_name`

varchar (384

), `register_date` datetime

);

生成隨機數字的函式:

delimiter $$

use `demo`$$

drop

function

if exists

`f_rand_num`$$

create

definer=`root`@`localhost`

function

`f_rand_num`(

start_num bigint,

end_num bigint

) returns

bigint(20

)begin

return

floor

(start_num + rand() * (end_num - start_num + 1

));end$$

delimiter ;

生成隨機n位字串的函式:

delimiter $$

use `demo`$$

drop

function

if exists

`f_rand_str`$$

create

definer=`root`@`localhost`

function

`f_rand_str`(l

int) returns

varchar(256

) charset utf8

begin

declare

chars_range varchar(128

) default

'abcdefghijklmnopqrstuvwxyz'

; declare

random_str varchar(256

) default

'';declare

iint

default 0;

while i < l do

set random_str = concat

(random_str, char(ascii

('a'

) + f_rand_num(0

, 25

)));

seti = i +1

; end

while

;

return random_str;

end$$

delimiter ;

插入資料的儲存過程:

delimiter $$

use `demo`$$

drop

procedure

if exists

`p_make_data`$$

create

definer=`root`@`localhost`

procedure

`p_make_data`(l

int)

begin

declare

iint

default 0;

while i < l do

insert

into

`t_member` (`member_no`, `user_name`, `register_date`)

values

(f_rand_num(100000000000

, 999999999999

), f_rand_str(8

), '2016-08-01'

); set

i = i + 1

;

if (i % 1000 = 0) then

select

@i;end

if;end

while

; end$$

delimiter ;

附一些測試sql:

-- 呼叫過程

call

p_make_data(500000

);-- 一些測試sql

select

f_rand_num(100000000000

, 999999999999

);select

f_rand_str(8

);select

ord('97'

);select

substring('hello'

, 5, 1

);select

ascii

('a'

);select

char(97

);select

100% 5

;select

count

(1) from

t_member t

order

by t.`id`

desc

;

後來參考了一篇文章,它提及,轉換為myisam引擎插入資料速度會快很多,插入完畢後再轉換回來innodb引擎使用,另外文章中還提及了一些提高速度的小訣竅,大家可以去看:mysql快速儲存插入大量資料一些方法總結。

mssql如何快速插入大級別資料

提供兩個方法實現插入大級別資料 1.使用set nocount on transaction,2.推薦使用cte 1.加上set nocount on,並盡可能加上transaction truncate table customers go 清除干擾查詢 dbcc dropcleanbuffers...

排序總結 插入 快速

很好的乙個部落格 通俗易懂,參考。插入排序 include sort header.h void insert int a,int n else break 如果新插入的資料 已排序列的較大數,則不用繼續迴圈 puts 插入 快速排序,相對複雜,腦海中有乙個排序移動的過程,演算法就好寫了。快速排序 ...

mysql快速插入資料

如果innodb引擎,先在表結構中去掉除主鍵以外索引,進行如下調整 1 關閉binlog,對應引數是log bin 0 2 調整innodb flush log at trx commit 0 3 調整innodb io capacity 4000,innodb io capacity max 80...