Computer >> Computer tutorials >  >> Programming >> MySQL

How can we import CSV files into MySQL tables by using mysqlimport?


For importing CSV files into MySQL table we must have a CSV file i.e. a file having comma-separated values in it. Then we must have a MySQL table with the same name and structure. To illustrate it we are taking the following example −

Example

For example, we have Address.CSV file having the following data −

Name,LastName,Address

Mohan,     Sharma,   Sundernagar
Saurabh,   Arora,    Chandigarh
Rajesh,    Singh,    Lucknow

And we want to import these values into MySQL table named Address having the following structure −

mysql> DESCRIBE ADDRESS;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| Name     | varchar(20) | YES  |     | NULL    |       |
| LastName | varchar(20) | YES  |     | NULL    |       |
| Address  | varchar(20) | YES  |     | NULL    |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

Now, with the help of mysql import, along with some options, we can import the values of address.csv into MySQL table named ‘address’ −

C:\mysql\bin>mysqlimport --ignore-lines=1 --fields-terminated-by=, --verbose --local -u root query C:/mysql/bin/mysql-files/address.csv

Connecting to localhost

Selecting database query

Loading data from LOCAL file: C:/mysql/bin/mysql-files/address.csv into address

query.address: Records: 3 Deleted: 0 Skipped: 0 Warnings: 0
Disconnecting from localhost

mysql> Select * from Address;
+---------+----------+-------------+
| Name    | LastName | Address     |
+---------+----------+-------------+
| Mohan   | Sharma   | Sundernagar |
| Saurabh | Arora    | Chandigarh  |
| Rajesh  | Singh    | Lucknow     |
+---------+----------+-------------+
3 rows in set (0.00 sec)

The above result set shows that the values from CSV file has been imported into MySQL table.