dua27031 2017-06-06 13:41
浏览 76
已采纳

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

Okay, so I get around 100k-1M lines of text that I always import to a database. 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."
");
    }
}
$lines = null;

However, it takes waaayyy too long. Is there any faster way to do it, or am I stuck with this method?

PS. I don't want to use MySQL's "INSERT DATA INFILE".

  • 写回答

1条回答 默认 最新

  • dongyi2159 2017-06-06 14:51
    关注

    As written, you're running an insert statement for every line. 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); 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."
    ");
    }
    $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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)