1

我有一个读取 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';
4

1 回答 1

4

将您的数据分成块,通过每个块的记录数(我更喜欢这个),或者通过将您的数据分成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}')

更新:

对于 sharding ,这是一种实现:

$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']}')";
}
于 2013-10-02T21:56:04.457 回答