MySQL批量数据脚本

1、建表

创建dept表和emp表

create table dept (
    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 ''
);

create table emp (
    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
);
2、设置参数log_bin_trust_function_creators

防止后面大数据插入报错。
查看是否开启

show variables like 'log_bin_trust_function_creators';

开启

set global log_bin_trust_function_creators = 1;

如果MySQL重启后,上述参数就会失效,永久方法就是修改MySQL配置文件(my.cnf)。

3、创建函数,保证每条数据不同
1)随机产生字符串
# 用$$替换;,表示sql语句的结束
delimiter $$
# 创建函数,和返回值类型
create function rand_string(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, substring(chars_str, floor(1 + rand() * 52), 1));
         set i = i + 1;
    end while;
    return return_str;
end $$

如果要删除方法

drop function rand_string;
2)随机产生部门编号
# 用$$替换;,表示sql语句的结束
delimiter $$
create function rand_num() returns int(5)
begin
    declare i int default 0;
    set i = floor(100 + rand() * 10);
return i;
end $$
4、创建存储过程
1)创建往emp表中插入数据的存储过程
use bigData;
# 用$$替换;,表示sql语句的结束
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 + 1), rand_string(6), 'SALESMAN', 0001, curdate(), 2000, 400, rand_num());
    until i = max_num end repeat;
    # 提交
    commit;
end $$
2)创建往dept表中插入数据的存储过程
# 用$$替换;,表示sql语句的结束
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、调用存储过程
call insert_dept(100, 10);

在这里插入图片描述
接着试试插入大数据

call insert_emp(100001, 500000);

在这里插入图片描述
花了47秒的插入时间

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值