小编典典

将CSV文件直接导入MySQL

mysql

我想将csv文件导入到mysql中。

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

http://www.tech-
recipes.com/rx/2345/import_csv_file_direct_into_mysql/

但是csv中的列名称与数据库表中的列名称不同,我该怎么办?我想以编程方式来做。


阅读 293

收藏
2020-05-17

共1个答案

小编典典

您可以创建一个脚本来解析您的csv文件并将数据放入db。

就像是:

    $path = "yourfile.csv";
    $row = 1;
    if (($handle = fopen($path, "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $row++;
            $data_entries[] = $data ;

        }
        fclose($handle);
    }
    // this you'll have to expand
    foreach($data_entries as $line){
        $sql = "INSERT INTO ..."
        $db->execute($line);
    }
2020-05-17