php对mysql批量插入

1.数据一条一条插入 insert

echo 'start: 'date('Y-m-d H-i-s').PHP_EOL;
$count = 0;
for ($i = 1;$i <= 100000 ;$i++) {
    
    
    $add_data = [
        'id'       => $i,
        'username' => 'user'.$i,
        'sex'      => mt_rand(1,2),
        'age'      => mt_rand(10,60),
    ];

    $res = Db::connect('db_test')->table('tf_user')->insert($add_data);
    if ($res) {
    
    
        $count ++ ;
    }
}
echo 'over: 'date('Y-m-d H-i-s').PHP_EOL;
echo "成功添加".$count."个数据。".PHP_EOL;

10W条数据,用时近85分钟。上面的代码,需要的内存少一些。执行的时间比较久。

2.insertAll 批量一次插入多条

$all_data = [];
echo 'start: 'date('Y-m-d H-i-s').PHP_EOL;
$begin = 100001;
$end   = 200000;
$count = 0;
$total_count = 0;
for ($i = $begin;$i <= $end ;$i++) {
    
    
    $add_data = [
        'id'       => $i,
        'username' => 'user'.$i,
        'sex'      => mt_rand(1,2),
        'age'      => mt_rand(10,60),
    ];
    $all_data[] = $add_data;
    if (count($all_data) == 5000) {
    
      //一次插入5000条
        $count = Db::connect('db_test')->table('tf_user')->insertAll($all_data);
        $total_count += $count;
        $all_data = []; // 重置
    }
}
echo 'over: 'date('Y-m-d H-i-s').PHP_EOL;
echo '完成添加'.$total_count."条";

用时不到6分钟,第二个程序明显用时快了很多,但是需要的内存会大一些。

insertAll 方法生成的sql:

INSERT INTO `tf_user` (`id` , `username` , `sex` , `age`) VALUES ( 100001,'user100001',2,47 ) , ( 100002,'user100002',2,26 ) , ( 100003,'user100003',1,10 ) , ( 100004,'user100004',2,10 ) , ( 100005,'user100005',2,50 )

转载:插入10W数据的两个程序比较

猜你喜欢

转载自blog.csdn.net/qq_39004843/article/details/105920974
今日推荐