Mysql使用存儲過程快速添加百萬數(shù)據(jù)的示例代碼
為了體現(xiàn)不加索引和添加索引的區(qū)別,需要使用百萬級的數(shù)據(jù),但是百萬數(shù)據(jù)的表,如果使用一條條添加,特別繁瑣又麻煩,這里使用存儲過程快速添加數(shù)據(jù),用時(shí)大概4個(gè)小時(shí)。
創(chuàng)建一個(gè)用戶表
CREATE TABLE `t_sales` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '用戶名', `password` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT '密碼 MD5存儲', `register_time` timestamp NULL DEFAULT NULL COMMENT '注冊時(shí)間', `type` int(1) DEFAULT NULL COMMENT '用戶類型 1,2,3,4 隨機(jī)', PRIMARY KEY (`id`), KEY `idx_username` (`username`) USING BTREE )
然后創(chuàng)建存儲過程,批量添加數(shù)據(jù)。
- 用戶名以常量和數(shù)字拼接
- 密碼是MD5密碼
- 注冊時(shí)間是當(dāng)前時(shí)間隨機(jī)往前推幾天
- type是取1-4隨機(jī)范圍值
create procedure salesAdd() begin declare i int default 11; while i <= 4000000 do insert into blog.t_sales (`username`,`password`,`register_time`,type) values (concat("jack",i),MD5(concat("psswe",i)),from_unixtime(unix_timestamp(now()) - floor(rand() * 800000)),floor(1 + rand() * 4)); set i = i + 1; end while; end
然后調(diào)用存儲過程
call salesAdd()
改進(jìn)版
雖然使用存儲過程添加數(shù)據(jù)相對一個(gè)個(gè)添加更加便捷,快速,但是添加幾百萬數(shù)據(jù)要花幾個(gè)小時(shí)時(shí)間也是很久的,后面在網(wǎng)上找到不少資料,發(fā)現(xiàn)mysql每次執(zhí)行一條語句都默認(rèn)自動提交,這個(gè)操作非常耗時(shí),所以在在添加去掉自動提交。設(shè)置 SET AUTOCOMMIT = 0;
create procedure salesAdd() begin declare i int default 1; set autocommit = 0; while i <= 4000000 do insert into blog.t_sales (`username`,`password`,`register_time`,type) values (concat("jack",i),MD5(concat("psswe",i)),from_unixtime(unix_timestamp(now()) - floor(rand() * 800000)),floor(1 + rand() * 4)); set i = i + 1; end while; set autocommit = 1; end
執(zhí)行時(shí)間387秒,約為六分鐘,其中還有一半時(shí)間用于md5、隨機(jī)數(shù)的計(jì)算。
[SQL]
call salesAdd();
受影響的行: 0
時(shí)間: 387.691s
到此這篇關(guān)于Mysql使用存儲過程快速添加百萬數(shù)據(jù)的文章就介紹到這了,更多相關(guān)Mysql添加百萬數(shù)據(jù)內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。