MySQL1分钟内插入百万数据

$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那么会大大缩短入库时间。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章