技术&日志

MySQL-批量入库优化

MySQL批量入库的方式

循环一条一条入库

批量入库

通过程序组合 insert into (字段) tbl vlaues(), vlaues(), vlaues(),...

事务入库

        $autoCommit = (isset($this->startTransaction) ? !$this->startTransaction : true);
        $ids = array();
        if ($autoCommit) {
            $this->startTransaction();
        }
        foreach ($multiInsertData as $insertData) {
            if ($dataKeys !== null) {
                // apply column-names if given, else assume they're already given in the data
                $insertData = array_combine($dataKeys, $insertData);
            }
            $id = $this->insert($tableName, $insertData);
            if (!$id) {
                if ($autoCommit) {
                    $this->rollback();
                }
                return false;
            }
            $ids[] = $id;
        }
        if ($autoCommit) {
            $this->commit();
        }

使用 LOAD DATA INFILE 文件导入

Tip: 通过PHP程序处理好对应格式的内容生成文件, 然后放到数据库服务器中导入操作.

imagecode.txt

http://www.qyule01.fun/media/videos/tmb/000/005/451/1.jpg###100000
http://pic.rmb.bdstatic.com/81923c4cd60b8731b09cc55a0ee82cb8.jpeg###100000
http://pcookie.cnzz.com/app.gif?&cna=Q/1fFKG8SggCAXRVIh2iBCTo###100000
http://inews.gtimg.com/newsapp_ls/0/6134659193_150120/0###100000

load data local infile'/Users/home/xx/temp/xxyun/imagecode.txt'into table imagecode fields terminated by'###'lines terminated by'\n'(url,code);

测试数据

vbox-ubuntu-16.04 2G2核

// 写入一个文件-本地vbox服务器 run time total :0.47590112686157

// 本地vbox服务器-耗费时间: run time total :46.867498874664
// 本地vbox服务器-去除rand函数: run time total :48.011456012726
// 本地vbox服务器-去除var_dump函数: run time total :0.12039113044739
// 本地vbox服务器-使用insertMulti函数 : run time total :43.925640106201

// 内网服务器-耗费时间: run time total :42.424664020538

相关资料

MySQL-关于load data local-详细文档

–secure-file-priv选项问题的解决方法 # show global variables like '%secure_file_priv%';

  • secure_file_priv 为 NULL 时,表示限制mysqld不允许导入或导出。
  • secure_file_priv 为 /tmp 时,表示限制mysqld只能在/tmp目录中执行导入导出,其他目录不能执行。
  • secure_file_priv 没有值时,表示不限制mysqld在任意目录的导入导出。

MySQL LOAD DATA INFILE – 加载没有主键的文件实战

发表评论