目录
创建表
设置参数 log_bin_trust_function_creators
创建函数
创建随机字符串函数
创建随机数函数
创建存储过程
调动存储过程
场景:领导让创建一个千万级别的数据进行一个压力测试
#############创建部门表##################################
create table dept (
id int UNSIGNED PRIMARY key AUTO_INCREMENT,
deptno MEDIUMINT UNSIGNED not null default 0,
dename varchar(255) not null default "",
loc varchar(255) not null default ""
)
员工表
################员工表#########################################
create table emp (
id int UNSIGNED PRIMARY key AUTO_INCREMENT,
empno MEDIUMINT UNSIGNED not null default 0,
ename 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
)
插入前参设置(如果报this function has none of deterministis...)
show variables like '%log_bin_trust_function_creators%';
set global log_bin_trust_function_creators = 1
创建函数保证每个数据都不同
DELIMITER $$
create function rand_string(n INT) RETURNS VARCHAR(255)
BEGIN
DECLARE char_str VARCHAR(100) DEFAULT 'abcdefghigklmnopqrstwvuxyzABCDEFGHIGKLMNOPQRSTWVUXYZ';
DECLARE RESULT_STR VARCHAR(255) DEFAULT '';
DECLARE i INT DEFAULT 0;
WHILE i< n DO
set RESULT_STR = CONCAT(RESULT_STR,SUBSTRING(char_str,FLOOR(1+RAND()*52),1));
set i= i+1;
END WHILE;
RETURN RESULT_STR;
END $$
DELIMITER $$
create function rand_num() RETURNS INT
BEGIN
DECLARE i INT DEFAULT 0;
set i= FLOOR(100+RAND()*10);//范围在100到110
RETURN i;
END $$
创建插入emp的存储函数
#################max_num表示插入的数据量###################################
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),'销售',0001,CURDATE(),1000,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,dename,loc)VALUES((start+i),rand_string(10),rand_string(6));
UNTIL i = max_num
END REPEAT;
COMMIT;
END $$
调用存储函数插入数据
##########部门表插入10条数据#########33
call insert_dept(100,10);
###############员工表插入2000000万数据#####
call insert_emp(1000,2000000);
测试数据是插入成功了,就是太慢了