How can we import the text file, having some line prefixes, into MySQL table?


Suppose if we have a line prefix in the text file then with the help of using ‘LINES STARTING BY’ option we can ignore that prefix and import correct data into MySQL table. It can be understood with the help of the following example −

Example

Suppose we are using ‘VALUE’ as the ‘LINE PREFIX’ in the text file as follows −

id,         Name,     Country,        Salary
VALUE:105,  Chum*,    Marsh,USA,      11000
106,        Danny*,   Harrison,AUS,   12000

Now while importing this text file into MySQL table then we need to mention ‘LINES STARTING BY’ option also in the query as follows −

mysql> LOAD DATA LOCAL INFILE 'd:\A.txt' INTO table employee8_tbl FIELDS TERMINATED BY ',' ESCAPED BY '*' LINES STARTING BY 'Value:' IGNORE 1 ROWS;
Query OK, 1 row affected (0.07 sec)
Records: 1 Deleted: 0 Skipped: 0 Warnings: 0

Now, we can see what has been imported with the help of the following query −

mysql> LOAD DATA LOCAL INFILE 'd:\A.txt' INTO table employee8_tbl FIELDS TERMINATED BY ',' ESCAPED BY '*' LINES STARTING BY 'Value:' IGNORE 1 ROWS;
Query OK, 1 row affected (0.07 sec)
Records: 1 Deleted: 0 Skipped: 0 Warnings: 0

Now, we can see what has been imported with the help of the following query −

mysql> Select * from employee8_tbl;
+------+----------------+----------+--------+
| Id   | Name           | Country  | Salary |
+------+----------------+----------+--------+
| 105  | Chum,Marsh     | USA      |  11000 |
+------+----------------+----------+--------+
1 row in set (0.00 sec)

MySQL import only one record in the table because we have used line prefix i.e. ‘VALUE:’ before the first line hence it ignores the line which does not have line prefix. Now, suppose if we add another line in the text file with line prefix ‘VALUE:’ then MySQL will upload this line too −

id,          Name,                Country,    Salary
Value:105,   Chum*,               Marsh,USA,  11000
106,         Danny*,Harrison,     AUS,        12000
Value:107,   Raman*,Kumar,        IND,        25000
mysql> LOAD DATA LOCAL INFILE 'd:\A.txt' INTO table employee8_tbl FIELDS TERMINATED BY ',' ESCAPED BY '*' LINES STARTING BY 'Value:' IGNORE 1 ROWS;
Query OK, 2 rows affected (0.07 sec)
Records: 1 Deleted: 0 Skipped: 0 Warnings: 0

Now, we can see what has been imported with the help of the following query −

mysql> Select * from employee8_tbl;
+------+----------------+----------+--------+
| Id   | Name           | Country  | Salary |
+------+----------------+----------+--------+
| 105  | Chum,Marsh     | USA      |  11000 |
| 107  | Raman,Kumar    | IND      |  25000 |
+------+----------------+----------+--------+
2 rows in set (0.00 sec)

Updated on: 20-Jun-2020

150 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements