Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import CSV file directly into MySQL

i want to import csv file into mysql.. something like:

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_directly_into_mysql/

but column names in csv and that in database table are different what should i do? i want to do it programmatically..

like image 541
ehmad Avatar asked Nov 10 '10 11:11

ehmad


People also ask

How do I import a CSV file into MySQL?

In the Format list, select CSV. Changing format-specific options. If the csv file is delimited by a character other than a comma or if there are other specifications to the csv files, we can change it in this portion. Click Go to start importing the csv file and the data will be successfully imported into MySQL.

How do I import a CSV file into MySQL workbench?

Importing CSV file using MySQL Workbench The following are steps that you want to import data into a table: Open table to which the data is loaded. Review the data, click Apply button. MySQL workbench will display a dialog “Apply SQL Script to Database”, click Apply button to insert data into the table.


2 Answers

but column names in csv and that in database table are different what should i do?

Not a problem. You can specify which CSV column gets imported into which database column.

LOAD DATA INFILE syntax

By default, when no column list is provided at the end of the LOAD DATA INFILE statement, input lines are expected to contain a field for each table column. If you want to load only some of a table's columns, specify a column list:

LOAD DATA INFILE 'persondata.txt' INTO TABLE persondata (col1,col2,...);

What I like to do when I find the INFILE syntax too complicated is use a graphical client like HeidiSQL to click together the proper column order (it has a graphical preview) and copy+paste the generated SQL query.

like image 187
Pekka Avatar answered Sep 21 '22 08:09

Pekka


You can create a script to parse your csv file and to put the data into db.

Something like:

    $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);
    }
like image 37
Elzo Valugi Avatar answered Sep 23 '22 08:09

Elzo Valugi