Dump all tables in CSV format using ‘mysqldump’

First, I can give you the answer for one table:

The trouble with all these INTO OUTFILE or --tab=tmpfile (and -T/path/to/directory) answers is that it requires running mysqldump on the same server as the MySQL server, and having those access rights.

My solution was simply to use mysql (not mysqldump) with the -B parameter, inline the SELECT statement with -e, then massage the ASCII output with sed, and wind up with CSV including a header field row:

Example:

 mysql -B -u username -p password database -h dbhost -e "SELECT * FROM accounts;" \
 | sed "s/\"/\"\"/g;s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g"

“id”,”login”,”password”,”folder”,”email”
“8”,”mariana”,”xxxxxxxxxx”,”mariana”,””
“3”,”squaredesign”,”xxxxxxxxxxxxxxxxx”,”squaredesign”,”[email protected]
“4”,”miedziak”,”xxxxxxxxxx”,”miedziak”,”[email protected]
“5”,”Sarko”,”xxxxxxxxx”,”Sarko”,””
“6”,”Logitrans
Poland”,”xxxxxxxxxxxxxx”,”LogitransPoland”,””
“7”,”Amos”,”xxxxxxxxxxxxxxxxxxxx”,”Amos”,””
“9”,”Annabelle”,”xxxxxxxxxxxxxxxx”,”Annabelle”,””
“11”,”Brandfathers and
Sons”,”xxxxxxxxxxxxxxxxx”,”BrandfathersAndSons”,””
“12”,”Imagine
Group”,”xxxxxxxxxxxxxxxx”,”ImagineGroup”,””
“13”,”EduSquare.pl”,”xxxxxxxxxxxxxxxxx”,”EduSquare.pl”,””
“101”,”tmp”,”xxxxxxxxxxxxxxxxxxxxx”,”_”,”[email protected]

Add a > outfile.csv at the end of that one-liner, to get your CSV file for that table.

Next, get a list of all your tables with

mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"

From there, it’s only one more step to make a loop, for example, in the Bash shell to iterate over those tables:

 for tb in $(mysql -u username -ppassword dbname -sN -e "SHOW TABLES;"); do
     echo .....;
 done

Between the do and ; done insert the long command I wrote in Part 1 above, but substitute your tablename with $tb instead.

Leave a Comment