MYSQL -Import Data from Delimited Data

Loading CSV or any delimited data files to MySQL Database. This is a very common task for the developer and the only thing that I think of is LOAD DATA INFILE.

The LOAD DATA INFILE statement reads rows from a text file into a table at a very high speed.

Here, I will explain how to get the data loaded directly from CSV to MySQL database using commands.

For more information, feel free to refer https://dev.mysql.com/doc/refman/5.7/en/load-data.html

a) Copy the complete CSV file data including header

LOAD DATA LOCAL INFILE 'path/of/csv/file'
INTO TABLE <TABLE NAME>
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'

Path: '/home/user/file_name.csv' or in windows 'C:/path/file_name.csv'
FIELDS TERMINATED BY ',': Divides the line data into Fields

Example: A table with three columns say A,B,C and CSV file is as follows
a,b,c
aa,bb,cc
aaa,bbb,ccc

By terminating by delimited ',' fields table would look like

A B C
a b c
aa bb cc
aaa bbb ccc

LINES TERMINATED BY '\n': Line Breaker

b) Copy the complete CSV file data excluding header


LOAD DATA LOCAL INFILE 'path/of/csv/file'
INTO TABLE <TABLE NAME>
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

IGNORE 1 LINES: Ignores the first line of the CSV File

c) If data sequence in the file and table are different.


LOAD DATA LOCAL INFILE 'path/of/csv/file'
INTO TABLE <TABLE NAME> 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(Column1,Column3,Column2);

Assume data sequence and tables fields are not matching we can include rearranging the data by using(Column1, Column3, Column2)

d) Create a new field with computed values

LOAD DATA LOCAL INFILE 'path/of/csv/file'
INTO TABLE <TABLE NAME> 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(Column1,@Column3,@Column2,@NewColumn)
SET NewColumn = (@Column2 / @Column3);

In the above example we have NewColumn value by computing the column value of Column2 and Column3

SET NewColumn = (@Column2 / @Column3);


e) Create a new field with Auto-increament Id


LOAD DATA LOCAL INFILE 'path/of/csv/file'
INTO TABLE <TABLE NAME> 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
IGNORE 1 LINES
(Column1,@Column3,@Column2,@NewColumn)
SET id = NULL;

To create a new autoincrement field on the table just  SET id = NULL; or SET id = '\N';


Other issues.

how to 'load data infile' on Amazon RDS?

You need to use LOAD DATA LOCAL INFILE as the file is not on the MySQL server, but is on the machine you are running the command from.
--local-infile=1

Comments

Popular posts from this blog

Using Redis in PHP for handling background Jobs

DrillDown using Flot Charts

Securely setting Files and Folder permissions on Laravel 5