Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Import Multiple csv files into a MySQL Database

Is there a way to import multiple csv files at the same time into a MySQL database? Some sort of batch import?

I'm on Mac OSX running a MAMP server.

I have 185 csv files that I need to import into a MySQL table. I can import them individually using phpMyAdmin's import tab, but it would take a long time. Does anyone know if there is a better way?

like image 290
Laxmidi Avatar asked Dec 16 '11 19:12

Laxmidi


2 Answers

Use a shell script like this:

#!/usr/bin/env bash
cd yourdirectory
for f in *.csv
do
        mysql -e "USE yourDatabase LOAD DATA LOCAL INFILE '"$f"'INTO TABLE yourtable"
done
like image 146
nazar554 Avatar answered Oct 06 '22 20:10

nazar554


There's a little PHP script for you:

#!/usr/bin/php
<?
mysql_connect('localhost','root','root'); // MAMP defaults
mysql_select_db('yourdatabase');
$files = glob('*.csv');
foreach($files as $file){
    mysql_query("LOAD DATA INFILE '".$file."' INTO TABLE yourtable");
}

See the MySQL Manual for LOAD DATA INFILE options which fit your documents.

like image 21
konsolenfreddy Avatar answered Oct 06 '22 20:10

konsolenfreddy