我有一个任务,我需要解析一个非常大的文件,并将结果写入mysql数据库。 “非常大”意味着我们正在讨论约1.4GB的CSV数据,总计约1000万行文本。解析一个非常大的文件到mysql
事情不是“怎么做”,但如何做到这一点快。我的第一个方法是在没有任何速度优化的情况下使用php,然后让它运行几天直到完成。不幸的是,它现在已经运行了48小时,并且只处理了总文件的2%。因此,这不是一种选择。
文件格式如下:
A:1,2
其中逗号的量隔开的数字继“:”可以是0-1000。该示例数据集必须进入一个表,如下所示:
| A | 1 |
| A | 2 |
所以现在,我没有这样说:
$fh = fopen("file.txt", "r");
$line = ""; // buffer for the data
$i = 0; // line counter
$start = time(); // benchmark
while($line = fgets($fh))
{
$i++;
echo "line " . $i . ": ";
//echo $i . ": " . $line . "<br>\n";
$line = explode(":", $line);
if(count($line) != 2 || !is_numeric(trim($line[0])))
{
echo "error: source id [" . trim($line[0]) . "]<br>\n";
continue;
}
$targets = explode(",", $line[1]);
echo "node " . $line[0] . " has " . count($targets) . " links<br>\n";
// insert links in link table
foreach($targets as $target)
{
if(!is_numeric(trim($target)))
{
echo "line " . $i . " has malformed target [" . trim($target) . "]<br>\n";
continue;
}
$sql = "INSERT INTO link (source_id, target_id) VALUES ('" . trim($line[0]) . "', '" . trim($target) . "')";
mysql_query($sql) or die("insert failed for SQL: ". mysql_error());
}
}
echo "<br>\n--<br>\n<br>\nseconds wasted: " . (time() - $start);
这显然是不以任何方式速度进行了优化。任何提示重新开始?我应该换用另一种语言吗?
第一我脑子里的事情就是使用'MySQLi'或'PDO',这样你就可以利用准备好的语句。 – Passerby
如果你的输入数据是一个CSV文件,也许你可以使用LOAD DATA INFILE,更多信息:http://dev.mysql.com/doc/refman/5.0/en/load-data.html – m4t1t0