MySQL1分钟内插入百万数据

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_40012791/article/details/87103637
$arr =[
    [
        'name' => 'testname1',
        'age' => 18,
    ],
    [
        'name' => 'testname2',
        'age' => 19,
    ],
    [
        'name' => 'testname3',
        'age' => 18,
    ],
];
//将格式化后的数据分片
$splitData = array_chunk($arr, 20000, true);
//mysql执行时间
ini_set('max_execution_time', 0);
//mysql连接
@mysql_pconnect("localhost", "root", "root") or die('connect failed');
@mysql_select_db("test") or die('select db failed');
//这一步很重要 取消mysql的自动提交
mysql_query('SET AUTOCOMMIT=0');
mysql_query('set names utf8');

$begin =  microtime(true);
$sql='';
if (!empty($splitData) && is_array($splitData)) {
    $sql = sprintf("INSERT INTO `user` (`name`,age) VALUES ");

    foreach($splitData as $items) {
        foreach ($items as $key=>$item){
            $itemStr = '( ';
            $itemStr .= sprintf("'%s', %d",$item['name'], (int)$item['age']);
            $itemStr .= '),';
            $sql .= $itemStr;
        }
    }

    // 去除最后一个逗号,并且加上结束分号
    $sql = rtrim($sql, ',');
    $sql .= ';';

    mysql_query($sql);

    //插入1W提交一次
    if ($key % 10000 == 0) {
        mysql_query("commit");
    }

}

$end = microtime(true);

echo "用时 " . round($end - $begin, 3) . " 秒 <hr/>";

原理:mysql插入数据库,插入时候并没有提交到mysql表里,在insert后面需要执行commit操作才会插入数据库。默认mysql是自动提交,如果关闭自动提交,在insert几十万数据在进行commit那么会大大缩短入库时间。

猜你喜欢

转载自blog.csdn.net/qq_40012791/article/details/87103637
今日推荐