MYSQL automatically insert csv files from folder using mysqlimport

房东的猫 提交于 2019-12-05 03:43:04

问题


I would like to import around 3000 CSV files from a specified "folder" automatically at a designated time. Everyday the CSV files will be updated to include new data.

I understand that I should use the command line tool "mysqlimport" and --replace option, (as sometimes old data will be altered)


回答1:


load data local infile 'uniq.csv' into table tblUniq(field1, field2, field3)
fields terminated by ','
enclosed by '"'
lines terminated by '\n'

This is an optional solution, the only thing you'll need is an PHP\Perl\Python script to itreate over all of the files, and insert them one by one

PHP code:

<?php

    $basedir = "/path/to/dir"
    if ($handle = opendir($basedir)) {
      while(false !== ($entry = readdir($handle))) {
        $query = "LOAD DATA LOCAL INFILE $basedir$entry
                    INTO TABLE tableName
                    FIELDS
                    TERMINATED BY ','
                    OPTIONALLY ENCLOSED BY '\"'
                    ESCAPED BY '\\'
                    LINES TERMINATED BY '\n'
                    IGNORE 1 LINES");
        if(DEBUG) { echo $query . "\n"; }
        if(!mysql_query($query)) {
          die('MySQL error: ' . mysql_error());
        }
      }
    } else {
      echo "Could not open $basedir";
    }
    ?>


来源:https://stackoverflow.com/questions/22269825/mysql-automatically-insert-csv-files-from-folder-using-mysqlimport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!