将csv文件导入MYSQL的最快方法

时间:2015-06-09 07:11:12

标签: php mysql csv

此方法将csv文件上传到mysql。但是对于csv文件中的数千个数据,上传数据很烦人需要花费大量时间。             

        $deleterecords = "TRUNCATE TABLE discount"; //empty the table of its current records
        mysql_query($deleterecords);
        //readfile($name);
        //Import uploaded file to Database
        $handle = fopen($name, "r");

        $i=0;
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        if($i>0){
            $import="INSERT into discount(id,title,expired_date,amount,block)values('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."')";
        //imports data serially to the allocated columns.
            mysql_query($import) or die(mysql_error());//query
        }
        $i=1;
        }
        fclose($handle);
       //closing the handle
       // print "Import done ";
       ?>

Can anyone suggest faster method for uploading data ?

5 个答案:

答案 0 :(得分:4)

您可以直接将MYSQL链接到它并使用以下SQL语法上传信息,而不是编写脚本以从CSV文件中提取信息。

要将Excel文件导入MySQL,请先将其导出为CSV文件。从生成的CSV文件中删除CSV标题以及Excel可能放在CSV文件末尾的空数据。

然后您可以通过运行:

将其导入MySQL表
load data local infile 'uniq.csv' into table tblUniq fields terminated by ','
  enclosed by '"'
  lines terminated by '\n'
    (uniqName, uniqCity, uniqComments)

阅读:Import CSV file directly into MySQL

答案 1 :(得分:1)

使用LOAD DATA INFILE语句。 https://dev.mysql.com/doc/refman/5.1/en/load-data.html

将数据加载到临时表中,并使用该表将一个语句插入主表。

答案 2 :(得分:1)

不要进行多次插入,而是构建一个大查询并执行单个插入。

<?php
$deleterecords = "TRUNCATE TABLE discount"; //empty the table of its current records
mysql_query($deleterecords);
//readfile($name);
//Import uploaded file to Database
$handle = fopen($name, "r");

$i=0;
$what_to_insert = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if($i>0){
        array_push($what_to_insert, "('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."')");
    }
    $i=1;
}
fclose($handle);
if (count($what_to_insert)>0){
    $import="INSERT into discount(id,title,expired_date,amount,block) values " . implode(",", $what_to_insert);
    mysql_query($import) or die(mysql_error());//query
}
?>

答案 3 :(得分:1)

您可以这种方式插入数据。这是在表中插入行的默认方式。

    $deleterecords = "TRUNCATE TABLE discount"; //empty the table of its current records
    mysql_query($deleterecords);
    //readfile($name);

    //Import uploaded file to Database
    $handle = fopen($name, "r");

    $i=0;

    $ins = "INSERT into discount(id,title,expired_date,amount,block) values ";

    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

    if($i>0){

    $import .= $ins."('".$data[0]."','".$data[1]."','".$data[2]."','".$data[3]."','".$data[4]."'),";
    //imports data serially to the allocated columns.

    }

    $import = rtrim($import,',');
    mysql_query($import) or die(mysql_error());//query
    $i=1;
    }
    fclose($handle);
   //closing the handle
   // print "Import done ";
   ?>

答案 4 :(得分:1)

如果phpMyAdmin可用,您可以使用CSV导入功能。