How to insert csv file data into MySQL database

MySQL have this load data function, where we can insert data to a table from external files like csv, txt etc.
The process is quite simple, 1st lets login to mysql via terminal/console.

mysql -u root -p

Enter your MySQL password. Change root to any username(MySQL users) you would wish to login to MySQL.

mysql>

Now lets run the command.

mysql> LOAD DATA LOCAL INFILE ‘/var/www/site/site_users.csv’
INTO TABLE site_users FIELDS
TERMINATED BY ‘;’
ENCLOSED BY ‘”‘
LINES TERMINATED BY ‘\n’
IGNORE 1 LINES;

You will see this if command ran successfully:

Query OK, 370 rows affected (0.00 sec)
Records: 370  Deleted: 0  Skipped: 0  Warnings: 0

In the 1st line, we load a file from local dir and that is the reason we used ‘LOCAL’.
2nd line will insert the data into site_users table.
In the 3rd line we tell the command to break the fields by ; . You can check your csv file in txt format that whether its ; or comma(,).
4th line means that data is enclosed with the double quotes.
And lines are terminated by \n.
Last line will ignore the 1st line, which usually represents the data headers.

One thing i would like to mention here, make sure that the table fields and csv columns sequence matches.
Like name, address, phone are in the table, csv will also be name, address, phone. Which means data will be inserted into the right field.
And yeh column name can be changed, that does not matter like in table first_name and in csv name. What i mean to say here is that the sequence of fields need to match that right data goes to the right field.

That’s it.

  • sulley

    I encounter errors as some of the columns are actually foreign key constraints. How ? There is a suggestion to turn off foreign_key_checks, but this isn’t advisable. Is there a proper way to do this ?

  • kepler

    helpful