MYSQL import data from csv using LOAD DATA INFILE MYSQL import data from csv using LOAD DATA INFILE mysql mysql

MYSQL import data from csv using LOAD DATA INFILE


You can use LOAD DATA INFILE command to import csv file into table.

Check this link MySQL - LOAD DATA INFILE.

LOAD DATA LOCAL INFILE 'abc.csv' INTO TABLE abcFIELDS 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 hold 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 docs.Beware that such overwrite does not solve the security issue but rather just an acknowledge that you are aware and willing to take the risk.


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_nameFIELDS TERMINATED BY ',' ENCLOSED BY '"'LINES TERMINATED BY '\r\n'IGNORE 1 LINES;


Before importing the file, you must need to prepare the following:

  • A database table to which the data from the file will be imported.
  • A CSV file with data that matches with the number of columns of thetable and the type of data in each column.
  • The account, which connects to the MySQL database server, has FILEand INSERT privileges.

Suppose we have following table :

enter image description here

CREATE TABLE USING FOLLOWING QUERY :

CREATE TABLE IF NOT EXISTS `survey` (  `projectId` bigint(20) NOT NULL,  `surveyId` bigint(20) NOT NULL,  `views` bigint(20) NOT NULL,  `dateTime` datetime NOT NULL);

YOUR CSV FILE MUST BE PROPERLY FORMATTED FOR EXAMPLE SEE FOLLOWING ATTACHED IMAGE :

enter image description here

If every thing is fine.. Please execute following query to LOAD DATA FROM CSV FILE :

NOTE : Please add absolute path of your CSV file

LOAD DATA INFILE '/var/www/csv/data.csv' INTO TABLE survey FIELDS TERMINATED BY ',' ENCLOSED BY '"'LINES TERMINATED BY '\r\n'IGNORE 1 LINES;

If everything has done. you have exported data from CSV to table successfully