Master MySQL Backups: Commands for Single DB, Multiple DBs, Compression & Restoration
This guide explains how to use mysqldump to back up individual databases, multiple databases, all databases, specific tables, and how to compress backups, include drop statements, export only schema, and restore data using both interactive and non‑interactive MySQL commands, plus an automated backup script.
MySQL Backup Database
Backup a single database
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --database DBNAME > filename.sqlBackup multiple databases
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --database DB1 DB2 DB3 > filename.sqlBackup all databases
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --all-databases > filename.sqlBackup specific tables
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" DBNAME TABLE1 > filename.sqlBackup specific multiple tables
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" DBNAME TABLE1 TABLE2 > filename.sqlThe -B parameter
Adding -B makes the dump file contain CREATE DATABASE and USE statements, so you do not need to create the target database manually before restoring.
Compressing backups with gzip
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --database DBNAME | gzip > filename.sql.gzIncluding drop statements
Use --add-drop-database to include DROP DATABASE statements and --add-drop-table to include DROP TABLE statements in the dump.
Exporting only schema
mysqldump -hHOST -PPORT -uUSER -p"PASSWORD" --no-data DB1 DB2 > filename.sqlRestoring a dump
Interactive method: mysql -uUSER -p"PASSWORD" DBNAME < dumpfile.sql Using the source command inside the MySQL console: mysql> source dumpfile.sql Non‑interactive method with -e:
mysql -uUSER -p"PASSWORD" -e "use DBNAME; source dumpfile.sql"Automatic backup script (bash)
#!/bin/bash
backupdir=/data/mysqlbak
time=$(date +%Y%m%d-%H%M)
mysqldump -hHOST -PPORT -uroot -p"PASSWORD" --all-databases --single-transaction --default-character-set=utf8 | gzip > $backupdir/mysql$time.sql.gz
find $backupdir -name "mysql*.sql.gz" -type f -mtime +7 -exec rm {} \; > /dev/null 2>&1Create the backup directory, make the script executable, and add a cron job (e.g., 00 3 * * * /data/mysqlbak/mysqlbak.sh) to run it daily.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Raymond Ops
Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
