简体   繁体   English

有没有更快的方法使用PHP将数据从文件导入MySQL?

[英]Is there a faster way to import data from a file to MySQL using php?

Okay, so I get around 100k-1M lines of text that I always import to a database. 好的,所以我得到大约100k-1M的文本行,我总是导入到数据库中。 The code that i use is as follows: 我使用的代码如下:

$lines = new SplFileObject('/home/file.txt');
while(!$lines->eof()) {
    $lines->next();       //Skipping first line
    $row = explode(',',$lines);
    for($i = 0; $i<4; $i++){
        if(!isset($row[$i])){
            $row[$i] = null;
        }
    }
    $y = (float) $row[1];
    $z = (float) $row[2];
    $load_query = "INSERT IGNORE INTO new (datetime_gmt,field2,field3)
    VALUES ('".$row[0]."','".$y."','".$z."');";

    if(!$mysqli->query($load_query)){
      die("CANNOT EXECUTE".$mysqli->error."\n");
    }
}
$lines = null;

However, it takes waaayyy too long. 但是,它需要waaayyy太长时间。 Is there any faster way to do it, or am I stuck with this method? 有没有更快的方法,或者我坚持这种方法?

PS. PS。 I don't want to use MySQL's "INSERT DATA INFILE". 我不想使用MySQL的“INSERT DATA INFILE”。

As written, you're running an insert statement for every line. 如上所述,您正在为每一行运行insert语句。 It'll be much faster if you compile a single multi-insert statement in the format of INSERT INTO table (foo, bar) VALUES (1, 2), (3, 4), (5, 6); 如果以INSERT INTO table (foo, bar) VALUES (1, 2), (3, 4), (5, 6);的格式编译单个多插入语句,它会快得多INSERT INTO table (foo, bar) VALUES (1, 2), (3, 4), (5, 6); that is executed once at the end. 在最后执行一次。 Something along the lines of this, though it could be cleaned up more. 有点像这样的东西,虽然它可以被清理得更多。

$lines = new SplFileObject('/home/file.txt');
$load_query = "INSERT IGNORE INTO new (datetime_gmt,field2,field3)
    VALUES ";
while(!$lines->eof()) {
    $lines->next();       //Skipping first line
    $row = explode(',',$lines);
    for($i = 0; $i<4; $i++){
        if(!isset($row[$i])){
            $row[$i] = null;
        }
    }
    $y = (float) $row[1];
    $z = (float) $row[2];
    $load_query .= "('".$row[0]."','".$y."','".$z."'),";
}

if(!$mysqli->query(rtrim($load_query, ','))) {
    die("CANNOT EXECUTE".$mysqli->error."\n");
}
$lines = null;

Also keep make sure the data is trusted. 还要确保数据是可信的。 If the file can come from an outside user, appending directly to the query string creates an SQL injection vector. 如果文件可以来自外部用户,则直接追加到查询字符串会创建SQL注入向量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM