Parse the csv data import method for mysql

  • 2020-07-21 06:58:41
  • OfStack

mysql has its own csv engine, which allows you to import data from csv into the mysql database much faster than batch programs written through php or python.
Concrete implementation code examples:

load data infile '/tmp/file.csv' into table _tablename (set character utf8) 
fields terminated by ','
enclosed by '"'
lines terminated by '\r\n'; 

Some of the 1 keywords in this code are explained as follows:
fields terminated by ": This refers to the field terminator in the csv file, that is, the delimiter between the data;
enclosed by ": Indicates the envelope character;
lines terminated by ": refers to the line terminator
The csv format is described in detail in the csv document (RFC4180). The main points are:
(1) Fields are separated by ", "(comma), and data rows are separated by \r\n;
(2) The string is enclosed in half-corner double quotes, and the double quotes of the string itself are represented by two double quotes.
With the above explanation, you should have a better understanding of the data import code in detail.

Similarly, csv data can be imported into mysql database, and the data table in mysql can also be exported to csv file. The exported code example:

select * from tablename into outfile '/tmp/data.txt' 
fields terminated by ','
optionally enclosed by '"'
lines terminated by '\n'; 

When you export data from the database to a file, to import data into the database, you must adhere to the format defined in the file at the time of the export.

Related articles: