小碗汤 · 2019年10月16日

利用procedure批量插入数据

正文

  要求在页面查询到5000条数据,为了方便插入,准备用shell脚本写curl命令调用自己写的代码接口,但是速度慢,而且写的时候遇到点儿小问题,故用sql语句写了这个功能
  由于operationlog表中的ts字段为13位的时间戳,所以采用了截取的方式。

DROP TABLE IF EXISTS `operationlog`;
CREATE TABLE `operationlog` (
  `sn` int(11) NOT NULL AUTO_INCREMENT,
  `opl` varchar(8) NOT NULL,
  `src` varchar(32) NOT NULL,
  `pid` varchar(32) DEFAULT NULL,
  `ts` varchar(13) NOT NULL,
  PRIMARY KEY (`sn`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

drop procedure if exists batchAdd;

/*count1 循环次数 opl和src为operationlog的列*/
create procedure batchAdd(in count1 int,in opl varchar(32),in src varchar(32))
begin
    declare a int;
    set a=0;
    while a<count1 do
        begin
            /*延时1s*/
            select sleep(1);
            /*获取时间戳1523285555.207000,后面3位是0,现在的需求是ts为13位,即带ms的*/
            select @time1:=unix_timestamp(now(3));
            /*将1523285555.207000的.去掉*/
            select @time1:=replace(@time1, '.', '');
            /*取1523285555207000左边13位*/
            select @time1:=left(@time1, 13);
            /*生成sql,进行insert*/
            insert into operationlog(opl, src, pid, ts) values(opl, src, '1111', @time1);
            /*a加1*/
            set a = a + 1;
        end;

    end while;
end;

--查看procedure
show procedure status;

--调用该procedure
call batchAdd(10, 'INFO', 'AJG');

--删除procedure
drop procedure batchAdd;

create procedure batchAdd如图所示:

batchAdd_procedure

创建好procedure后,可以通过call batchAdd(10, 'INFO', 'AJG');来调用,如下图所示:

call_batchAdd



本公众号免费提供csdn下载服务,海量IT学习资源,如果你准备入IT坑,励志成为优秀的程序猿,那么这些资源很适合你,包括但不限于java、go、python、springcloud、elk、嵌入式 、大数据、面试资料、前端 等资源。同时我们组建了一个技术交流群,里面有很多大佬,会不定时分享技术文章,如果你想来一起学习提高,可以公众号后台回复【2】,免费邀请加技术交流群互相学习提高,会不定期分享编程IT相关资源。


扫码关注,精彩内容第一时间推给你

image

推荐阅读
关注数
1
文章数
116
微信公众号【我的小碗汤】博主,分享技术文章和记录编程中遇到的问题及解决方案,工作中提高效率的工具,推送原创文章及优秀文章等
目录
极术微信服务号
关注极术微信号
实时接收点赞提醒和评论通知
安谋科技学堂公众号
关注安谋科技学堂
实时获取安谋科技及 Arm 教学资源
安谋科技招聘公众号
关注安谋科技招聘
实时获取安谋科技中国职位信息