一、建表
# 新建库
create database bigData;
use bigData;
#1 建表dept
create table dept(
id int auto_increment,
deptno mediumint not null default 0,
dname varchar(20) not null default "",
loc varchar(13) not null default "",
primary key(id)
);
#2 建表emp
create table emp(
id int auto_increment,
empno mediumint not null default 0, -- 编号
ename varchar(20) not null default "", -- 名字
job varchar(9) not null default "", -- 工作
mgr mediumint not null default 0, -- 上级编号
hiredate date not null, -- 入职时间
sal decimal(7,2) not null, -- 薪水
comm decimal(7,2) not null, -- 红利
deptno mediumint not null default 0, -- 部门编号
primary key(id) -- 主键
);
二、设置参数log_bin_trust_function_creators
创建函数,假如报错:This function has none of DETERMINISTIC.....
#由于开启过慢查询日志,因为我们开启了bin-log,我们就必须为我们的function指定一个参数。
show variables like 'log_bin_trust_function_creators';
set global log_bin_trust_function_creators=1;
#这样添加了参数以后,如果mysqld重启,上述参数又会消失,永久方法:
windows下my.ini[mysqld]加上log_bin_trust_function_creators=1
linux下letc/my.cnf 下my.cnf[mysqld]加上log_bin_trust_function_creators=1
三、创建函数,保证每条数据都不同 3.1 随机产生字符串delimiter $$
create function rand_str(n int) returns varchar(255)
begin
declare chars_str varchar(100) default 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
declare return_str varchar(255) default '';
declare i int default 0;
while i < n do
set return_str = concat(return_str,substr(chars_str,floor(1+rand()*52),1));
set i = i + 1;
end while;
return return_str;
end $$
delimiter ;
3.2 随机产生部门编号
# 用于随机产生部门编号
delimiter $$
create function rand_num() returns int(5)
begin
declare i int default 0;
set i = floor(100 + rand()*10);
return i;
end $$
delimiter ;
# 删除语法
# drop funciton rand_num;
四、创建存储过程
4.1 创建往dept表插入数据的存储过程
# 执行存储过程,往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_str(10),rand_str(8));
until i = max_num
end repeat;
commit;
end $$
delimiter ;
4.2 创建往emp表插入数据的存储过程
delimiter $$
create procedure insert_emp(in start int(10),in max_num int(10))
begin
declare i int default 0;
# set autocommit = 0 把autocommit设置为0 开启事务
set autocommit = 0;
repeat
set i=i+1;
insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno)
values
((start+i),rand_str(6),'SALESMAN',0001,curdate(),2000,400,rand_num());
until i = max_num
end repeat;
commit;
end $$
delimiter ;
五、调用存储过程
delimiter ;
call insert_dept(100, 10);
# 执行存储过程,往emp表添加50万条数据
delimiter ;
call insert_emp(100001, 500000);
视频教程