我在一个XML文件中有大约30K条记录,并且这个文件一直在更新。
我正在尝试插入并更新一个MySQL数据库。
这是我想使用的代码,但它运行非常慢,有谁有任何想法来提高它的性能吗?
// getting xml file
$dom = new DOMDocument();
$dom->load('products.xml');
// getting xml nodes using xpath
$xpath = new DOMXPath($dom);
$productid = $xpath->query('//NewDataSet/Product/ProductId');
$price = $xpath->query('//NewDataSet/Product/Price');
// Reading all nodes and if mach found in db update price, else insert as new record**
for($i=0;$i<$allNodes->length;$i++){
$testproductid = $productid->item($i)->nodeValue;
$testprice = $price->item($i)->nodeValue;
if(mysql_num_rows(mysql_query("Select productid from test where productid ='$testproductid'"))){
mysql_query("UPDATE test SET price = '$testprice' WHERE productid = '$testproductid'");
}else{
mysql_query("INSERT INTO test (price, productid) VALUES ('$testprice','$testproductid')");
}
}发布于 2011-04-06 05:30:05
首先,这一行可能会导致不良行为:
if(mysql_num_rows(mysql_query("Select productid from test where productid ='$testproductid'")))如果mysql_query()失败了会发生什么?做一些像这样的事情:
$res = mysql_query("Select productid from test where productid ='$testproductid'");
if ($res) {
... CODE HERE ...
}productid是索引吗?此外,您还可以将查询格式化为:
Select productid from test where productid ='$testproductid' LIMIT 1在这种情况下,MySQL不会查找更多的记录。另外,尝试在on single insert语句中插入多条记录。请看以下内容:
http://dev.mysql.com/doc/refman/5.0/en/insert-speed.html
看一下REPLACE命令。这将替换SELECT/UPDATE/INSERT条件,但这可能不会大大提高性能。
发布于 2011-04-06 05:23:12
首先,我建议复习一些MySQL。其次,通过在SQL域上使用主键,您可以使用一个更高级的productid语句:insert ... on duplicate key update ...
It's gonna halve your database lookups for the first part,因为您在插入/更新之前要做一个额外的测试。
其次,XML可能不是跨平台文件的最佳解决方案。你使用这个有什么特别的原因吗?
发布于 2011-04-06 05:27:14
为什么要有两个查询,而一个查询就足够了?
$sql = "INSERT INTO test (price, productid) " .
"VALUES ('$testprice','$testproductid') " .
"ON DUPLICATE KEY UPDATE";
if(!$query = mysql_query($sql))
trigger_error(mysql_error());你也可以尝试用SimpleXML来代替DOMDocument,但从我用谷歌搜索得到的信息来看,似乎没有任何有记录的速度差异。
https://stackoverflow.com/questions/5558675
复制相似问题