Import CSV files to MySQL/MariaDB table

You can import data from CSV (Comma-Separated Values) files directly to MySQL tables using LOAD DATA statement or by using MySQL's own mysqlimport tool.

To be able to import the files, you'll need to be able to figure out the following properties of the CSV files;

  • Line terminator
  • Field terminator
  • Field enclosure

The following example is for importing source.csv with the following content into target_db.target_table;

"aa","ab","ac"
"ba","bb","bc"
"ca","cb","cc"

Method 1: LOAD DATA

LOAD DATA LOCAL INFILE 'source.csv' INTO target_db.target_table FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n';

Method 2: mysqlimport

mysqlimport --local --fields-terminated-by="," --fields-enclosed-by="\"" target_db.target_table source.csv  

Sign up for The Ultimate MySQL Bootcamp: Go from SQL Beginner to Expert course on Udemy to learn more.


Written by Mohd Shakir Zakaria. Last updated on 2019-02-12