MySql(二十二)--批量插入数据库脚本

MySql(二十二)--批量插入数据库脚本_第1张图片

1.建表

create database bigData;
use bigData;

create table dept(
`id` INT unsigned primary key NOT NULL AUTO_INCREMENT,
`deptno` mediumint unsigned not NULL DEFAULT 0,
`dname` varchar(20) not null default "",
`loc`  VARCHAR(13)  not NULL DEFAULT ""
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

create table emp(
 id int unsigned primary key not null auto_increment,
 empno int unsigned not null default 0,
 ename varchar(20) not null default "",
 job varchar(20) not null default "",
 mgr int unsigned not null default 0,
 hiredate date not null,
 sal decimal(7,2) not null,
 comm decimal(7,2) not null,
 deptno int unsigned not null default 0
)ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

2.设置参数log_bin_trust_function_creators

MySql(二十二)--批量插入数据库脚本_第2张图片

MySql(二十二)--批量插入数据库脚本_第3张图片

3.创建函数,保证每条数据都不同

随机产生字符串

delimiter $$
create function rand_string(n int) returns varchar(255)
begin 
 declare chars_str varchar(100) default 'qazwsxedcrfvtgbyhnujmikolpQAZWSXEDCRFVTGBYHNUJMIKOLP';
 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 $$
 create function rand_num() returns int(5)
 begin  
   declare i int default 0;
   set i = floor(100 + rand()*10);
 return i;
end$$ 

4.创建存储过程

创建往emp表中插入数据的存储过程

delimiter $$
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 emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)
  values
  ((start+i),rand_string(6),'saleman',00001,curdate(),2000,400,rand_num());
  until i = max_num
  end repeat;
  commit;
end $$

创建往dept表中插入数据的存储过程

delimiter $$
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 dept(deptno,dname,loc)
  values((start+i),rand_string(10),rand_string(8));
 until i = max_num
 end repeat;
 commit;
end $$

5.调用存储过程

dept

delimiter ;
call insert_dept(100,10);

 

MySql(二十二)--批量插入数据库脚本_第4张图片

emp

执行存储过程,往emp表中添加50万条数据

delimiter ;
call insert_emp(100001,500000);

 

你可能感兴趣的:(mysql)