批量插入測試指令碼
阿新 • • 發佈:2020-09-19
使用指令碼進行大資料量的批量插入,對特定情況下測試資料集的建立非常有用。
1)建立tb_dept_bigdata(部門表)
create table tb_dept_bigdata( id int unsigned primary key auto_increment, deptno mediumint unsigned not null default 0, dname varchar(20) not null default '', loc varchar(13) not null default '' )engine=innodb default charset=utf8;
2)建立tb_emp_bigdata(員工表)
create table tb_emp_bigdata( id int unsigned primary key auto_increment, empno mediumint unsigned not null default 0,/*編號*/ empname varchar(20) not null default '',/*名字*/ job varchar(9) not null default '',/*工作*/ mgr mediumint unsigned not null default 0,/*上級編號*/ hiredate date not null,/*入職時間*/ sal decimal(7,2) not null,/*薪水*/ comm decimal(7,2) not null,/*紅利*/ deptno mediumint unsigned not null default 0 /*部門編號*/ )engine=innodb default charset=utf8;
3)開啟log_bin_trust_function_creators引數
由於在建立函式時,可能會報:This function has none of DETERMINISTIC.....因此我們需開啟函式建立的信任功
可通過set globallog_bin_trust_function_creators=1的形式開啟該功能,也可通過在my.cnf中永久配置的方式開啟該功能,在[mysqld]下配置log_bin_trust_function_creators=1
一、建立函式,保證每條資料都不同
建立隨機生成字串的函式
delimiter $$ drop function if exists rand_string; create function rand_string(n int) returns varchar(255) begin declare chars_str varchar(52) default 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; declare return_str varchar(255) default ''; declare i int default 0; while i<n do set return_str=concat(return_str,substring(chars_str,floor(1+rand()*52),1)); set i=i+1; end while; return return_str; end $$
建立隨機生成編號的函式
delimiter $$ drop function if exists rand_num; create function rand_num() returns int(5) begin declare i int default 0; set i=floor(100+rand()*100); return i; end $$
二、建立儲存過程用於批量插入資料
建立往tb_dept_bigdata表中插入資料的儲存過程
delimiter $$ drop procedure if exists insert_dept; create procedure insert_dept(in start int(10),in max_num int(10)) begin declare i int default 0; set autocommit=0; repeat set i=i+1; insert into tb_dept_bigdata (deptno,dname,loc) values(rand_num(),rand_string(10),rand_string(8)); until i=max_num end repeat; commit; end $$
建立往tb_emp_bigdata表中插入資料的儲存過程
delimiter $$ drop procedure if exists insert_emp; create procedure insert_emp(in start int(10),in max_num int(10)) begin declare i int default 0; set autocommit=0; repeat set i=i+1; insert into tb_emp_bigdata (empno,empname,job,mgr,hiredate,sal,comm,deptno) values((start+i),rand_string(6),'developer',0001,curdate(),2000,400,rand_num()); until i=max_num end repeat; commit; end $$
三、具體執行過程批量插入資料
#1.首先執行隨機生成字串的函式
#2.然後執行隨機生成編號的函式。
#3.檢視函式是否建立成功。
#4.執行插入資料的儲存過程,並檢視其建立情況。
#5.執行儲存過程,插入資料。
a.首先執行insert_dept儲存過程。
說明:deptno的範圍[100,110),因為deptno的值使用了rand_num()函式。
b.然後執行insert_emp儲存過程。
說明:tb_emp_bigdata表中deptno編號的範圍[100,110),使用rand_num()函式。
注:對於部門表的deptno和員工表中deptno的資料都使用了rand_num()函式進行賦值,確保兩邊的值能對應。
四、刪除函式與儲存過程
#刪除函式
drop function rand_num; drop function rand_string;
#刪除儲存過程
drop procedure insert_dept; drop procedure insert_emp;
五、總結
① 注意mysql中函式和儲存過程的寫法。
② 注意儲存過程的呼叫,call procedurename。
③ 注意開啟對函式的信任,log_bin_trust_function_creators引數。