1. 程式人生 > 實用技巧 >php & mysql 插入大量資料三種方式的效能差距

php & mysql 插入大量資料三種方式的效能差距

數量級5000條


<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\admin\model\Model;
use app\common\logic\Xls;
// 將資訊匯入到表裡面去
class putQxxXls extends Command
{
    protected function configure()
    {
        $this->setName('putQxxXls')->setDescription('Here is the remark ');
    }

    protected function execute(Input $input, Output $output)
    {
        $path = APP_PATH . 'admin/lib/qxxdata.xls';
        $model = new Model();
        $data = Xls::excel2data($path);
        $fileds = ["qy_name", "second_name", "qy_address"];


        $time = Xls::getMs();

        // float(1493)
        // 使用原生sql語句實現批量插入
        // array_walk($data, function (&$value, $key){
        //     array_walk($value, function(&$value1, $key1){
        //         $value1 = "'" . $value1 . "'";
        //     });
        //     $value = "(" .implode(',', $value). ")";
        // });
        // $data = implode(',', $data);
      
        // $sql1 = "INSERT INTO `crm_brandtest_qcc`(`qy_name`,`second_name`,`qy_address`)VALUES " .  $data;
        // $model->execute($sql1);

        // float(133122)
        // 使用tp的saveAll實現批量插入
        // array_walk($data, function (&$value, $key) use ($fileds){
        //     for ($i=0; $i < count($fileds); $i++) { 
        //         $value[$fileds[$i]] = $value[$i];
        //         unset($value[$i]);
        //     }
        // });
        // $model->saveAll($data);

        // float(133514)
        // 在迴圈裡面save實現批量插入
        // foreach($data as $k => $v){
        //     for ($i=0; $i < count($fileds); $i++) { 
        //         $v[$fileds[$i]] = $v[$i];
        //         unset($v[$i]);
        //     }
        //     $model->insert($v);
        // }
        var_dump(Xls::getMs() - $time);

    }
}