MYSQL import data from csv using LOAD DATA INFILE

2018-12-31 20:09发布

I am importing some data of 20000 rows from a CSV file into Mysql.

Columns in the CSV are in a different order than MySQL table's columns. How to 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.

Please suggest auto syntax for importing data to Mysql.

10条回答
梦寄多情
2楼-- · 2018-12-31 20:38

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 abc
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(col1, col2, col3, col4, col5...);
查看更多
爱死公子算了
3楼-- · 2018-12-31 20:38

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);
查看更多
有味是清欢
4楼-- · 2018-12-31 20:41

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.

table.sql

id //field 1

name //field2

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'; 
查看更多
一个人的天荒地老
5楼-- · 2018-12-31 20:44

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;
查看更多
登录 后发表回答