批量数据插入 php mysql 速度



我有一个脚本,可以读取XML文件并将数据插入mysql数据库中。我的问题是它只插入一条记录,而我要插入 60 000 行数据,我希望它比插入行花一个小时更快。

我的脚本

$db_link = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('my_db');
//SIMPLEXML: Cleaned file is opened
$xml_source='cleanme.xml';
$xml=simplexml_load_file($xml_source);
//Reading each tag in the xml file
foreach($xml->Property as $prop){
    echo 'Reference '.$prop->Reference.'<br>';
    $ref_id=$prop->Reference;
//Reading sub tags in the xml file
 foreach($prop->Images->Image as $chk)
   {
    echo 'REF_ID '.$ref_id.' '.'ImageID '.$chk->ImageID.'<br>';
    $sql_refid = $ref_id;
    $sql_link =$chk->ImageID;
//Inserts data into to the database  
    $sql.="INSERT INTO prop_ref (id, ref, link) VALUES (NULL, '{$sql_refid}','{$sql_link}')";
   }   
}
mysql_query($sql);
echo 'Complete';

将数据分片为块,每个块的 # 条记录(我更喜欢这样),或者将数据分成n集,然后进行批量插入,例如

INSERT INTO `table_name` (id, ref, link) 
    VALUES (NULL, '{$sql_refid}', '{$sql_link}')
         , (NULL, '{$sql_refid}', '{$sql_link}')
         , (NULL, '{$sql_refid}', '{$sql_link}')
         , (NULL, '{$sql_refid}', '{$sql_link}')
         , (NULL, '{$sql_refid}', '{$sql_link}')
         , (NULL, '{$sql_refid}', '{$sql_link}')
         , (NULL, '{$sql_refid}', '{$sql_link}')
         , (NULL, '{$sql_refid}', '{$sql_link}')

更新:

对于分片,这里有一个实现:

$shardSize = 500;
$sql = '';
foreach ($data as $k => $row) {
    if ($k % $shardSize == 0) {
        if ($k != 0) {
            mysqy_query($sql);
        }
        $sql = 'INSERT INTO `dbTable` (id, ref, link) VALUES ';
    }
    $sql .= (($k % $shardSize == 0) ? '' : ', ') . "(NULL, '{$row['refid']}',  '{$row['link']}')";
}

最新更新