Last night I was asked by a client to export all of the tables into CSV format. I thought no problem. Then I saw the long list of table names! They wanted every one of them in CSV format! At that point, I started thinking about making a backup and then importing them all as CSV storage engine and then I realized CSV was disabled on the sandbox server! So, I thought well, I could try MySQL Query Browser, but then I figured I would still have to do it on a table-by-table basis. That is when I decided to go the Bash script route!
This lead to the formation of the brief script you see below. It simply connects to a given database, shows the list of tables, and then dumps out the contents in CSV format to individual files named
tablename.csv in the current directory. After just a few minutes of scripting, it was all over and I had a handy little script for the next time they or another client ask for the same thing!
Hopefully this script will be of some value to everyone else as well. Just be sure to change the configuration section to meet your needs.
Name the file something like: export_csv.sh. Then be sure to make it executable. In Linux, do something like "chmod a+x ./export_csv.sh" and you should be able to rock and roll.
If you want to have all of the scripts in a certain directory, you could either modify the script or just make the cirectory, "cd" into it, and then run the script. It assumes you want to create the files in the current working directory. To change that behavior, you could easily modify the "OUTFILE" variable to something like:
OUTFILE="/my_path/$TABLE.csv"
Anyway, here is the script for your enjoyment and use!
#!/bin/bash
#
# Simple script to crawl through all tables in a database and export to CSV format.
#
# Valcora: http://www.valcora.com
#
#### Begin Configuration ####
DB="mydb"
MYSQL_USER="root"
MYSQL_PASSWD="mypass"
MYSQL_HOST="127.0.0.1"
MYSQL_PORT="3306"
MYSQL="/usr/bin/mysql"
#### End Configuration ####
MYSQL_CMD="$MYSQL -u $MYSQL_USER -p$MYSQL_PASSWD -P $MYSQL_PORT -h $MYSQL_HOST"
TABLES=`$MYSQL --batch -N -D $DB -e "show tables"`
for TABLE in $TABLES
do
SQL="SELECT * FROM $TABLE;"
OUTFILE=$TABLE.csv
$MYSQL --database=$DB --execute="$SQL" | sed 's/\t/","/g;s/^/"/;s/$/"/;s/\n//g' > $OUTFILE
done
As always, be sure to test this script on a non-critical server first to ensure it is working to your satisfaction. There is no error trapping, so be sure you don't accidentally over-write important files!