Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dump all mysql tables into separate files automagically?

Tags:

mysqldump

I'd like to get dumps of each mysql table into separate files. The manual indicates that the syntax for this is

mysqldump [options] db_name [tbl_name ...] 

Which indicates that you know the table names before hand. I could set up the script that knows each table name now, but say I add a new table down the road and forget to update the dump script. Then I'm missing dumps for one or more table.

Is there a way to automagically dump each existing table into a separate file? Or am I going to have to do some script-fu; query the database, get all the table names, and dump them by name.

If I go the script-fu route, what scripting langauges can access a mysql database?

like image 719
user151841 Avatar asked Sep 08 '10 15:09

user151841


People also ask

How do I dump multiple tables in MySQL?

To dump multiple tables with multiple where conditions. Then, for second table, use ">>". It will append the previous dump file.


1 Answers

Here's a script that dumps table data as SQL commands into separate, compressed files. It does not require being on the MySQL server host, doesn't hard-code the password in the script, and is just for a specific db, not all db's on the server:

#!/bin/bash  # dump-tables-mysql.sh # Descr: Dump MySQL table data into separate SQL files for a specified database. # Usage: Run without args for usage info. # Author: @Trutane # Ref: http://stackoverflow.com/q/3669121/138325 # Notes: #  * Script will prompt for password for db access. #  * Output files are compressed and saved in the current working dir, unless DIR is #    specified on command-line.  [ $# -lt 3 ] && echo "Usage: $(basename $0) <DB_HOST> <DB_USER> <DB_NAME> [<DIR>]" && exit 1  DB_host=$1 DB_user=$2 DB=$3 DIR=$4  [ -n "$DIR" ] || DIR=. test -d $DIR || mkdir -p $DIR  echo -n "DB password: " read -s DB_pass echo echo "Dumping tables into separate SQL command files for database '$DB' into dir=$DIR"  tbl_count=0  for t in $(mysql -NBA -h $DB_host -u $DB_user -p$DB_pass -D $DB -e 'show tables')  do      echo "DUMPING TABLE: $DB.$t"     mysqldump -h $DB_host -u $DB_user -p$DB_pass $DB $t | gzip > $DIR/$DB.$t.sql.gz     tbl_count=$(( tbl_count + 1 )) done  echo "$tbl_count tables dumped from database '$DB' into dir=$DIR" 
like image 191
Trutane Avatar answered Oct 07 '22 17:10

Trutane