Save CSV files into mysql database

前端 未结 3 1468
旧时难觅i
旧时难觅i 2020-12-05 22:44

I have a lot of csv files in a directory. With these files, I have to write a script that put their content in the right fields and tables of my database. I am almost beginn

相关标签:
3条回答
  • 2020-12-05 22:57

    MySQL provides a wonderful feature that allows you to import a CSV file directly, in a single query.

    The SQL command you're looking for is LOAD DATA INFILE

    Manual page here: http://dev.mysql.com/doc/refman/5.1/en/load-data.html

    Quick example:

    LOAD DATA INFILE 'fileName'
     INTO TABLE tableName
     FIELDS TERMINATED BY '|' OPTIONALLY ENCLOSED BY '"'
     LINES TERMINATED BY '\n'
    (
    field1,
    field2,
    field3,
    @variable1,
    @variable2,
    etc
    )
    set
    (
    field4 = concat(@variable1,@variable2)
    );
    

    That's a fairly basic example, but it covers most of what you'd want. The manual page gives full details of how to do some very complex stuff with it.

    Hope that helps.

    0 讨论(0)
  • 2020-12-05 23:04

    after

    foreach ($row as $field) {
    echo $field . '<br />'; 
    

    You need to parse the result after ; like:

    $pieces = explode(";", $field);
    

    and then insert every piece into the database

    $sql = ' INSERT INTO X VALUES ("'.$pieces[0].'","'.$pieces[1].'","'.$pieces[2].'","'.$pieces[3].'","'.$pieces[4].'")';
    mysql_query($sql, $conn);
    
    0 讨论(0)
  • 2020-12-05 23:06

    Also mysqlimport can be used

    private function runImport($host, $username, $password, $schema, $csvFilePath) {
        $output = array();
        $cmd = "/usr/bin/mysqlimport --host=$host";
        $cmd .= ' --fields-terminated-by=\',\'  --fields-optionally-enclosed-by=\'"\' ';
        $cmd .= ' --user=' . $username . ' --password='. $password;
        $cmd .= " $schema $csvFilePath";
    
        exec($cmd, $output, $retVal);
    
        foreach ($output as $line) {
           echo "$line\n";
        }
    
        echo "\n\nReturn code : $retVal";
    }
    
    0 讨论(0)
提交回复
热议问题