Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL import data from csv using LOAD DATA INFILE

I am importing some data of 20,000 rows from a CSV file into MySQL.

Columns in the CSV file are in a different order than MySQL tables' columns. How can I automatically assign columns corresponding to MySQL table columns?

When I execute

LOAD DATA INFILE 'abc.csv' INTO TABLE abc

this query adds all data to the first column.

What is the auto syntax for importing data to MySQL?

like image 329
MANJEET Avatar asked Oct 05 '22 09:10

MANJEET


People also ask

How do I import CSV data 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 insert selected columns from a CSV file to a MySQL database using load data infile?

Load data into a table in MySQL and specify columns: LOAD DATA LOCAL INFILE 'file. csv' INTO TABLE t1 FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (@col1,@col2,@col3,@col4) set name=@col4,id=@col2 ; @col1,2,3,4 are variables to hold the csv file columns (assume 4 ) name,id are table columns.

Can you use to load data from a file into a table?

INTO OUTFILE statement is used to write data from a table to a file, the LOAD DATA statement reads the file back into the table. You can also use the mysqlimport utility that sends a LOAD DATA statement to the server to load data from file to table in MySQL.


2 Answers

You can use the LOAD DATA INFILE command to import a CSV file into a table.

Check the link MySQL - LOAD DATA INFILE.

LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abc
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);

For MySQL 8.0 users:

Using the LOCAL keyword holds security risks and as of MySQL 8.0 the LOCAL capability is set to False by default. You might see the error:

ERROR 1148: The used command is not allowed with this MySQL version

You can overwrite it by following the instructions in the documentation. Beware that such an overwrite does not solve the security issue, but rather is just an acknowledgment that you are aware and willing to take the risk.

like image 212
Saharsh Shah Avatar answered Oct 06 '22 23:10

Saharsh Shah


You probably need to set the FIELDS TERMINATED BY ',' or whatever the delimiter happens to be.

For a CSV file, your statement should look like this:

LOAD DATA INFILE 'data.csv' INTO TABLE tbl_name
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
like image 61
ckim Avatar answered Oct 06 '22 22:10

ckim