134

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MANJEET
  • 1,733
  • 2
  • 12
  • 21
  • 1
    There is a similar topic in http://stackoverflow.com/questions/11077801/import-csv-to-mysql-table/32949959#32949959 – marciomolusco Jul 23 '16 at 21:22
  • It happened to me, I found out that the text file was written with lines terminated by '\r' and I was trying to import the data expecting the lines to be terminated using the '\n' – Tamer Jan 29 '17 at 09:45
  • 3
    I wrote extensive tutorial to [load csv data into mysql](http://kedar.nitty-witty.com/blog/load-delimited-data-csv-excel-into-mysql-server) along with a [syntax generator tool in Excel](http://kedar.nitty-witty.com/blog/mysql-load-data-infile-syntax-generator-tool). It should be useful to readers. – mysql_user Jan 24 '18 at 09:27
  • Do *any* of the existing answers actually answer the question *"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?"*? They all instead *seem* to answer ***the more general question*** in the title of the question. Alternatively, is the question illogical or unclear? – Peter Mortensen Apr 11 '22 at 15:06

15 Answers15

218

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
63

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;
Sandeep
  • 1,504
  • 7
  • 22
  • 32
ckim
  • 994
  • 6
  • 7
56

Before importing the file, you 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 the table and the type of data in each column.
  • The account, which connects to the MySQL database server, has FILE and INSERT privileges.

Suppose we have the following table:

Enter image description here

Create the table using the 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 the following attached image:

Enter image description here

If everything is fine, please execute the following query to load data from the CSV file:

Note: Please add the 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 been done, you have exported data from the CSV file to the table successfully.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sunny S.M
  • 5,768
  • 1
  • 38
  • 38
  • How can we validate if CSV file have proper datatype for each column because by default it ignores invalid datatype. – Umar Abbas Jan 08 '16 at 13:38
17

Syntax:

LOAD DATA [LOW_PRIORITY | CONCURRENT] [LOCAL]
INFILE 'file_name' INTO TABLE `tbl_name`
CHARACTER SET [CHARACTER SET charset_name]
FIELDS [{FIELDS | COLUMNS}[TERMINATED BY 'string']]
[LINES[TERMINATED BY 'string']]
[IGNORE number {LINES | ROWS}]

See this example:

LOAD DATA LOCAL INFILE
'E:\\wamp\\tmp\\customer.csv' INTO TABLE `customer`
CHARACTER SET 'utf8'
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES;
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Md. Nashir Uddin
  • 730
  • 7
  • 20
12

Insert bulk more than 7,000,000 records in 1 minute in the database (superfast query with calculation):

    LOAD DATA LOCAL INFILE "'.$file.'"
    INTO TABLE tablename
    FIELDS TERMINATED by \',\'
    LINES TERMINATED BY \'\n\'
    IGNORE 1 LINES
    (isbn10,isbn13,price,discount,free_stock,report,report_date)
     SET RRP = IF(discount = 0.00,price-price * 45/100,IF(discount = 0.01,price,IF(discount != 0.00,price-price * discount/100,@RRP))),
         RRP_nl = RRP * 1.44 + 8,
         ID = NULL

RRP and RRP_bl are not in the CSV file, but we are calculating those and insert them after that.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
krunal panchal
  • 417
  • 4
  • 9
2

If you are running LOAD DATA LOCAL INFILE from the Windows shell, and you need to use OPTIONALLY ENCLOSED BY '"', you will have to do something like this in order to escape characters properly:

"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysql" -u root --password=%password% -e "LOAD DATA LOCAL INFILE '!file!' INTO TABLE !table! FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"^""' LINES TERMINATED BY '\n' IGNORE 1 LINES" --verbose --show-warnings > mysql_!fname!.out
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kikoz
  • 146
  • 4
  • What Windows shell? [CMD](https://en.wikipedia.org/wiki/Cmd.exe)? [PowerShell](https://en.wikipedia.org/wiki/PowerShell) (first introduced in 2006)? – Peter Mortensen Apr 11 '22 at 14:36
2

Let’s suppose you are using XAMPP and phpMyAdmin.

You have file name 'ratings.txt' table name 'ratings' and database name 'movies'.

If your XAMPP is installed in "C:\xampp", copy your "ratings.txt" file in the "C:\xampp\mysql\data\movies" folder.

LOAD DATA INFILE 'ratings.txt' INTO TABLE ratings FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 LINES;

This may work if you are doing this on localhost.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mohammad Arshi
  • 386
  • 2
  • 9
2

By these days (ending 2019) I prefer to use a tool like Convert CSV to SQL.

If you got a lot of rows, you can run partitioned blocks saving user mistakes when the CSV comes from a final user spreadsheet.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • There's a CSV Lint plug-in for Notepad++ that can do the same thing https://github.com/BdR76/CSVLint – BdR Oct 25 '21 at 19:22
2
  1. Edit my.ini file and add the following secure-file-priv = "" under [mysqld] section. Also if already any variable set for this then remove that.

  2. Then restart the MySQL service and execute the following command to check whether the value has been successfully changed or not:

    SHOW VARIABLES LIKE "secure_file_priv";

  3. Then you can execute the following query in the MySQL installed system and import the data,

    LOAD DATA INFILE "csv file location" INTO TABLE tablename
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\n'
    IGNORE 1 LINES
    (column1,column2,.....);
    

    Note: (column name separated by comma as per csv file)

  4. To add any CSV file from any other remote system you can also do the following after the above step:

    show global variables like 'local_infile';
    -- Note: if the value is OFF then execute the next command below
    set global local_infile=true; 
    -- check back again if the value has been set to ON or not
    
  5. Execute the following command to import data from CSV file from any other system,

    LOAD DATA LOCAL INFILE "csv file location" INTO TABLE tablename
    FIELDS TERMINATED BY ','
    LINES TERMINATED BY '\n'
    IGNORE 1 LINES
    (column1,column2,.....);
    -- column name separated by comma as per csv file
    
1

You can load data from a CSV or text file.

If you have a text file with records from a table, you can load those records within the table.

For example, if you have a text file, where each row is a record with the values for each column, you can load the records this way.

File table.sql

id //field 1

name //field2

File table.txt

1,peter

2,daniel

...

Example on Windows

LOAD DATA LOCAL INFILE 'C:\\directory_example\\table.txt'
INTO TABLE Table
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n';
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jorge T
  • 121
  • 1
  • 2
  • 9
1

You can try to insert like this:

LOAD DATA INFILE '/tmp/filename.csv' replace INTO TABLE [table name] FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' (field1,field2,field3);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Hozayfa
  • 11
  • 3
  • The last part, "(field1,field2,field3)", is different from most of the other answers. An explanation would be in order. E.g., what is the idea/gist? From [the Help Center](https://stackoverflow.com/help/promotion): *"...always explain why the solution you're presenting is appropriate and how it works"*. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/53476068/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Apr 11 '22 at 15:00
0

I was getting

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

This worked for me on Windows 8.1 64 bit using WAMP Server 3.0.6 64 bit:

  • I edited my.ini file from C:\wamp64\bin\mysql\mysql5.7.14.

  • Delete entry secure_file_priv c:\wamp64\tmp\ (or whatever directory you have here).

  • I stopped everything—with exit wamp, etc.—and restarted everything; then put my CVS file on C:\wamp64\bin\mysql\mysql5.7.14\data\u242349266_recur (the last directory being my database name)

  • I executed

     LOAD DATA INFILE 'myfile.csv'
    
     INTO TABLE alumnos
    
     FIELDS TERMINATED BY ','
    
     ENCLOSED BY '"'
    
     LINES TERMINATED BY '\r\n'
    
     IGNORE 1 LINES
    
  • ... and voilà!!!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Carlos Garcia
  • 359
  • 1
  • 5
  • 29
0

create A table in Mysql

CREATE TABLE Address_Book (  
    ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,   
    NAME VARCHAR(35) NOT NULL,   
    Email VARCHAR(35),  
    Mobile INT(12),   
    Address VARCHAR(45)  
); 

than create a csv file at location D:\\csvfiles\\address.csv

paste the below content into the csv file

ID, Name, Email, Mobile, Address

"1","Tushar Bhadwaj","jorge@abc.com","4848488","123 Park Street"

"2","Peter","peter@gma.com","4848485","321 Fake Avenue"

"3","Michael Clark","clark@rt.com","4848487","321 Park Avenue"

"4","James Franklin","james@lk.com","4848489","321 Fake Avenue"

enter image description here

And than execute the below command for import the csv file content---

LOAD DATA LOCAL INFILE 'D:\\csvfiles\\address.csv' 
INTO TABLE Address_Book 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
 LINES TERMINATED BY '\r\n'
  IGNORE 1 ROWS;

All the detail already provided in the page .In case you can't understand you can click on below link .The content is same as on page.

https://youtu.be/Gp7XYM_Hr3c

Stefan
  • 1,697
  • 15
  • 31
  • When promoting your own content (i.e. your youtube link) you need to make it's clear that it's yours. Please see https://stackoverflow.com/help/promotion – DavidW Dec 11 '22 at 09:49
  • All the detail already defined on the page if he/she can't understand then they can go for link – tushar bhardwaj Dec 12 '22 at 09:55
0

I can see that your CSV columns have different arrangements compared to the MySQL table columns. To specifically answer the problem, you need to map the columns of your CSV to your MySQL table by specifying the column list in LOAD DATA INFILE.

Here’s a simple example:

LOAD DATA INFILE ‘person.csv’ INTO TABLE person (lastname, firstname, middlename, …);

So, if your CSV columns are arranged like firstname, middlename, lastname,… this will fit in. Of course, you need other options like LINES TERMINATED BY and others as needed.

Here’s the specific link to the documentation.

Other details have already been mentioned in other answers.

Using the LOAD DATA INFILE have advantages for quick loading, even for large datasets. Today, there are tools where you can visually map CSV columns to MySQL table columns. Tools like Talend, Apache Nifi, and other tools mentioned here have these. Or you can use a cloud solution like Skyvia where a wizard is available to do just that.

0
LOAD DATA INFILE 'abc.csv' INTO TABLE abc fields terminated by '|' (@filecol1,@filecol2,@filecol3)
SET filecol =@filecol1, filecol2 =@filecol2, filecol3 =@filecol3

Here you would require to check your CSV how the fields are being terminated I worked on certain files. The Files may use , | ; \t etc

Sanjana
  • 16
  • 2
  • Please read [answer] and [edit] your answer to contain an explanation as to why this code would actually solve the problem at hand. Always remember that you're not only solving the problem, but are also educating the OP and any future readers of this post. – Adriaan Apr 06 '23 at 09:34