In mysql Load Data records the solution to the newline problem

  • 2020-05-15 02:17:17
  • OfStack

Here's the problem:

Table persons has two fields: id and name
Content in the text document persons.txt (where each line of fields is separated by tab) :
1 Bush
2 Carter
3 Bush

Import data into the persons table using load data local infile "persons.txt" into table persons from the mysql command line.

View the data in the persons table after import, corresponding to content 1 of persons.txt. But using statements
select distinct name from persons
Query, Bush appears twice in the result (the normal result would be Bush only once).

Reason analysis:

After analysis, it was found that the reason was that the newline character under windows was "\r\n", while mysql used "\n" to cut each row by default when load data was used. As a result, more invisible characters "\r" were inserted at the end of the name field inserted into the first two records in the table. That is to say, in the two Bush queries using the distinct keyword, the first end of the word has the carriage return character "\r ", while the second end does not.
Description:
1. mysql USES tab by default to split the fields of each line.
2. Since the newline under linux is "\n", the above problem will not occur under linux.

Modification method:
Simply specify "\r\n" to wrap the line when importing the data.
The modified import data statement is:


load data local infile  " persons.txt "  into table persons
lines terminated by  " \r\n " ;


Related articles: