mysql 数据备份(mysqldump)

*************************

mysqldump 使用

命令格式

root@7a72b2ffd688:/# mysqldump --help
mysqldump  Ver 8.0.25 for Linux on x86_64 (MySQL Community Server - GPL)
Copyright (c) 2000, 2021, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.Dumping structure and contents of MySQL databases and tables.
Usage: mysqldump [OPTIONS] database [tables]                          #导出指定数据库下的表
OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]     #导出多个数据库所有表
OR     mysqldump [OPTIONS] --all-databases [OPTIONS]                  #导出所有的数据库Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf
#配置文件的读取顺序:/etc/my.cnf /etc/mysql/my.cnf ~/.my.cnf The following groups are read: mysqldump client
The following options may be given as the first argument:
--print-defaults        Print the program argument list and exit.
--no-defaults           Don't read default options from any option file,except for login file.
--defaults-file=#       Only read default options from the given file #.
--defaults-extra-file=# Read this file after the global files are read.
--defaults-group-suffix=#Also read groups with concat(group, suffix)
--login-path=#          Read this path from the login file.#用户名、密码、端口-u, --user=name     User for login if not current user.-p, --password[=name] Password to use when connecting to server. If password isnot given it's solicited on the tty.-P, --port=#        Port number to use for connection.#导出所有数据库-A, --all-databases Dump all the databases. This will be same as --databaseswith all databases selected.#导出指定的数据库,多个数据库用空格间隔-B, --databases     Dump several databases. Note the difference in usage; inthis case no tables are given. All name arguments areregarded as database names. 'USE db_name;' will beincluded in the output.#导出数据库下指定的表--tables            Overrides option --databases (-B).#导出所有的表命名空间-Y, --all-tablespaces Dump all the tablespaces.#不导出表的命名空间-y, --no-tablespaces Do not dump any tablespace information.#创建数据库语句前,添加删除语句,默认不添加--add-drop-database Add a DROP DATABASE before each create.#创建表语句前,添加删除语句,默认添加--add-drop-table    Add a DROP TABLE before each create.(Defaults to on; use --skip-add-drop-table to disable.)#创建trigger前添加删除语句,默认不添加--add-drop-trigger  Add a DROP TRIGGER before each create.# insert语句前锁表--add-locks         Add locks around INSERT statements.(Defaults to on; use --skip-add-locks to disable.)--allow-keywords    Allow creation of column names that are keywords.# 从服务器上使用该参数时,执行stop slave,输出此时从机复制的master binary log的偏移量、文件名称备份完成后,执行start slave,从原位置开始主从复制
# 1 输出change master命令
# 2 在change master命令前加注释
# 该参数会锁定所有表(--loc-all-tables),除非使用--single-transactions参数--dump-slave[=#]    This causes the binary log position and filename of themaster to be appended to the dumped data output. Settingthe value to 1, will printit as a CHANGE MASTER commandin the dumped data output; if equal to 2, that commandwill be prefixed with a comment symbol. This option willturn --lock-all-tables on, unless --single-transaction isspecified too (in which case a global read lock is onlytaken a short time at the beginning of the dump - don'tforget to read about --single-transaction below). In allcases any action on logs will happen at the exact momentof the dump.Option automatically turns --lock-tables off.#主机上执行,不会停止主从服务,输出binary log的偏移量、文件名称
# 1 输出change master命令
# 2 在change master前加注释
# 该参数会锁定所有表(--lock-all-tables),除非使用--single-transactions参数--master-data[=#]   This causes the binary log position and filename to beappended to the output. If equal to 1, will print it as aCHANGE MASTER command; if equal to 2, that command willbe prefixed with a comment symbol. This option will turn--lock-all-tables on, unless --single-transaction isspecified too (in which case a global read lock is onlytaken a short time at the beginning of the dump; don'tforget to read about --single-transaction below). In allcases, any action on logs will happen at the exact momentof the dump. Option automatically turns --lock-tablesoff.# 导出数据时,创建一致性的数据快照,目前只支持innoDB存储引擎
# 使用该命令时,其他连接不能使用alter table、drop table、rename table、truncate table语句
# 该参数会自动关闭 --lock-tables--single-transaction Creates a consistent snapshot by dumping all tables in asingle transaction. Works ONLY for tables stored instorage engines which support multiversioning (currentlyonly InnoDB does); the dump is NOT guaranteed to beconsistent for other storage engines. While a--single-transaction dump is in process, to ensure avalid dump file (correct table contents and binary logposition), no other connection should use the followingstatements: ALTER TABLE, DROP TABLE, RENAME TABLE,TRUNCATE TABLE, as consistent snapshot is not isolatedfrom them. Option automatically turns off --lock-tables.--apply-slave-statements Adds 'STOP SLAVE' prior to 'CHANGE MASTER' and 'STARTSLAVE' to bottom of dump.--bind-address=name IP address to bind to.--character-sets-dir=name Directory for character set files.--column-statistics Add an ANALYZE TABLE statement to regenerate any existingcolumn statistics.(Defaults to on; use --skip-column-statistics to disable.)-i, --comments      Write additional information.(Defaults to on; use --skip-comments to disable.)--compatible=name   Change the dump to be compatible with a given mode. Bydefault tables are dumped in a format optimized forMySQL. The only legal mode is ANSI.Note: Requires MySQLserver version 4.1.0 or higher. This option is ignoredwith earlier server versions.--compact           Give less verbose output (useful for debugging). Disablesstructure comments and header/footer constructs.  Enablesoptions --skip-add-drop-table --skip-add-locks--skip-comments --skip-disable-keys --skip-set-charset.-c, --complete-insert Use complete insert statements.-C, --compress      Use compression in server/client protocol.-a, --create-options Include all MySQL specific create options.(Defaults to on; use --skip-create-options to disable.)-#, --debug[=#]     This is a non-debug version. Catch this and exit.--debug-check       This is a non-debug version. Catch this and exit.--debug-info        This is a non-debug version. Catch this and exit.--default-character-set=name Set the default character set.--delete-master-logs Delete logs on master after backup. This automaticallyenables --master-data.-K, --disable-keys  '/*!40000 ALTER TABLE tb_name DISABLE KEYS */; and'/*!40000 ALTER TABLE tb_name ENABLE KEYS */; will be putin the output.(Defaults to on; use --skip-disable-keys to disable.)-E, --events        Dump events.-e, --extended-insert Use multiple-row INSERT syntax that include severalVALUES lists.(Defaults to on; use --skip-extended-insert to disable.)--fields-terminated-by=name Fields in the output file are terminated by the givenstring.--fields-enclosed-by=name Fields in the output file are enclosed by the givencharacter.--fields-optionally-enclosed-by=name Fields in the output file are optionally enclosed by thegiven character.--fields-escaped-by=name Fields in the output file are escaped by the givencharacter.-F, --flush-logs    Flush logs file in server before starting dump. Note thatif you dump many databases at once (using the option--databases= or --all-databases), the logs will beflushed for each database dumped. The exception is whenusing --lock-all-tables or --master-data: in this casethe logs will be flushed only once, corresponding to themoment all tables are locked. So if you want your dumpand the log flush to happen at the same exact moment youshould use --lock-all-tables or --master-data with--flush-logs.--flush-privileges  Emit a FLUSH PRIVILEGES statement after dumping the mysqldatabase.  This option should be used any time the dumpcontains the mysql database and any other database thatdepends on the data in the mysql database for properrestore. -f, --force         Continue even if we get an SQL error.-?, --help          Display this help message and exit.--hex-blob          Dump binary strings (BINARY, VARBINARY, BLOB) inhexadecimal format.-h, --host=name     Connect to host.--ignore-error=name A comma-separated list of error numbers to be ignored ifencountered during dump.--ignore-table=name Do not dump the specified table. To specify more than onetable to ignore, use the directive multiple times, oncefor each table.  Each table must be specified with bothdatabase and table names, e.g.,--ignore-table=database.table.--include-master-host-port Adds 'MASTER_HOST=<host>, MASTER_PORT=<port>' to 'CHANGEMASTER TO..' in dump produced with --dump-slave.--insert-ignore     Insert rows with INSERT IGNORE.--lines-terminated-by=name Lines in the output file are terminated by the givenstring.-x, --lock-all-tables Locks all tables across all databases. This is achievedby taking a global read lock for the duration of thewhole dump. Automatically turns --single-transaction and--lock-tables off.-l, --lock-tables   Lock all tables for read.(Defaults to on; use --skip-lock-tables to disable.)--log-error=name    Append warnings and errors to given file.--max-allowed-packet=# The maximum packet length to send to or receive fromserver.--net-buffer-length=# The buffer size for TCP/IP and socket communication.--no-autocommit     Wrap tables with autocommit/commit statements.-n, --no-create-db  Suppress the CREATE DATABASE ... IF EXISTS statement thatnormally is output for each dumped database if--all-databases or --databases is given.-t, --no-create-info Don't write table creation info.-d, --no-data       No row information.-N, --no-set-names  Same as --skip-set-charset.--opt               Same as --add-drop-table, --add-locks, --create-options,--quick, --extended-insert, --lock-tables, --set-charset,and --disable-keys. Enabled by default, disable with--skip-opt.--order-by-primary  Sorts each table's rows by primary key, or first uniquekey, if such a key exists.  Useful when dumping a MyISAMtable to be loaded into an InnoDB table, but will makethe dump itself take considerably longer.--protocol=name     The protocol to use for connection (tcp, socket, pipe,memory).-q, --quick         Don't buffer query, dump directly to stdout.(Defaults to on; use --skip-quick to disable.)-Q, --quote-names   Quote table and column names with backticks (`).(Defaults to on; use --skip-quote-names to disable.)--replace           Use REPLACE INTO instead of INSERT INTO.-r, --result-file=name Direct output to a given file. This option should be usedin systems (e.g., DOS, Windows) that use carriage-returnlinefeed pairs (\r\n) to separate text lines. This optionensures that only a single newline is used.-R, --routines      Dump stored routines (functions and procedures).--set-charset       Add 'SET NAMES default_character_set' to the output.(Defaults to on; use --skip-set-charset to disable.)--set-gtid-purged[=name] Add 'SET @@GLOBAL.GTID_PURGED' to the output. Possiblevalues for this option are ON, COMMENTED, OFF and AUTO.If ON is used and GTIDs are not enabled on the server, anerror is generated. If COMMENTED is used, 'SET@@GLOBAL.GTID_PURGED' is added as a comment. If OFF isused, this option does nothing. If AUTO is used and GTIDsare enabled on the server, 'SET @@GLOBAL.GTID_PURGED' isadded to the output. If GTIDs are disabled, AUTO doesnothing. If no value is supplied then the default (AUTO)value will be considered.--dump-date         Put a dump date to the end of the output.(Defaults to on; use --skip-dump-date to disable.)--skip-opt          Disable --opt. Disables --add-drop-table, --add-locks,--create-options, --quick, --extended-insert,--lock-tables, --set-charset, and --disable-keys.-S, --socket=name   The socket file to use for connection.--server-public-key-path=name File path to the server public RSA key in PEM format.--get-server-public-key Get server public key--ssl-mode=name     SSL connection mode.--ssl-ca=name       CA file in PEM format.--ssl-capath=name   CA directory.--ssl-cert=name     X509 cert in PEM format.--ssl-cipher=name   SSL cipher to use.--ssl-key=name      X509 key in PEM format.--ssl-crl=name      Certificate revocation list.--ssl-crlpath=name  Certificate revocation list path.--tls-version=name  TLS version to use, permitted values are: TLSv1, TLSv1.1,TLSv1.2, TLSv1.3--ssl-fips-mode=name SSL FIPS mode (applies only for OpenSSL); permittedvalues are: OFF, ON, STRICT--tls-ciphersuites=name TLS v1.3 cipher to use.-T, --tab=name      Create tab-separated textfile for each table to givenpath. (Create .sql and .txt files.) NOTE: This only worksif mysqldump is run on the same machine as the mysqldserver.--triggers          Dump triggers for each dumped table.(Defaults to on; use --skip-triggers to disable.)--tz-utc            SET TIME_ZONE='+00:00' at top of dump to allow dumping ofTIMESTAMP data when a server has data in different timezones or data is being moved between servers withdifferent time zones.(Defaults to on; use --skip-tz-utc to disable.)-v, --verbose       Print info about the various stages.-V, --version       Output version information and exit.-w, --where=name    Dump only selected records. Quotes are mandatory.-X, --xml           Dump a database as well formed XML.--plugin-dir=name   Directory for client-side plugins.--default-auth=name Default authentication client-side plugin to use.--enable-cleartext-plugin Enable/disable the clear text authentication plugin.-M, --network-timeout Allows huge tables to be dumped by settingmax_allowed_packet to maximum value andnet_read_timeout/net_write_timeout to large value.(Defaults to on; use --skip-network-timeout to disable.)--show-create-table-skip-secondary-engine Controls whether SECONDARY_ENGINE CREATE TABLE clauseshould be dumped or not. No effect on older servers thatdo not support the server side option.--compression-algorithms=name Use compression algorithm in server/client protocol.Valid values are any combination of'zstd','zlib','uncompressed'.--zstd-compression-level=# Use this compression level in the client/server protocol,in case --compression-algorithms=zstd. Valid range isbetween 1 and 22, inclusive. Default is 3.#参数默认值
Variables (--variable-name=value)
and boolean options {FALSE|TRUE}        Value (after reading options)
--------------------------------------- ----------------------------------
all-databases                           FALSE
all-tablespaces                         FALSE
no-tablespaces                          FALSEadd-drop-database                       FALSE      #默认不在创建数据库前删除数据库
add-drop-table                          TRUE       #默认在创建表前加删除表
add-drop-trigger                        FALSE      #默认不在触发器前删除触发器
add-locks                               TRUE       #默认锁表where                                   (No default value)
#数据过滤,如 --where="id=1"、--where="name='gtlx'"allow-keywords                          FALSE
apply-slave-statements                  FALSE
bind-address                            (No default value)
character-sets-dir                      (No default value)
column-statistics                       TRUE
comments                                TRUE
compatible                              (No default value)
compact                                 FALSE
complete-insert                         FALSE
compress                                FALSE
create-options                          TRUE
databases                               FALSE
default-character-set                   utf8mb4
delete-master-logs                      FALSE
disable-keys                            TRUE
dump-slave                              0
events                                  FALSE
extended-insert                         TRUE
fields-terminated-by                    (No default value)
fields-enclosed-by                      (No default value)
fields-optionally-enclosed-by           (No default value)
fields-escaped-by                       (No default value)
flush-logs                              FALSE
flush-privileges                        FALSE
force                                   FALSE
hex-blob                                FALSE
host                                    (No default value)
ignore-error                            (No default value)
include-master-host-port                FALSE
insert-ignore                           FALSE
lines-terminated-by                     (No default value)
lock-all-tables                         FALSE
lock-tables                             TRUE
log-error                               (No default value)
master-data                             0
max-allowed-packet                      25165824
net-buffer-length                       1046528
no-autocommit                           FALSE
no-create-db                            FALSE
no-create-info                          FALSE
no-data                                 FALSE
order-by-primary                        FALSE
port                                    0
quick                                   TRUE
quote-names                             TRUE
replace                                 FALSE
routines                                FALSE
set-charset                             TRUE
single-transaction                      FALSE
dump-date                               TRUE
socket                                  (No default value)
server-public-key-path                  (No default value)
get-server-public-key                   FALSE
ssl-ca                                  (No default value)
ssl-capath                              (No default value)
ssl-cert                                (No default value)
ssl-cipher                              (No default value)
ssl-key                                 (No default value)
ssl-crl                                 (No default value)
ssl-crlpath                             (No default value)
tls-version                             (No default value)
tls-ciphersuites                        (No default value)
tab                                     (No default value)
triggers                                TRUE
tz-utc                                  TRUE
user                                    (No default value)
verbose                                 FALSE
plugin-dir                              (No default value)
default-auth                            (No default value)
enable-cleartext-plugin                 FALSE
network-timeout                         TRUE
show-create-table-skip-secondary-engine FALSE
compression-algorithms                  (No default value)
zstd-compression-level                  3

*************************

mysqldump 文件格式

mysqldump -u root -p --databases test test2 > test.backup:备份数据库test、test2

 root@7a72b2ffd688:/# mysqldump -u root -p --databases test test2 > test.backup
Enter password:
root@7a72b2ffd688:/# cat test.backup
-- MySQL dump 10.13  Distrib 8.0.25, for Linux (x86_64)
--
-- Host: localhost    Database: test
-- ------------------------------------------------------
-- Server version   8.0.25/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;--
-- Current Database: `test`
--# 数据库test如果不存在,则创建数据库
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `test` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 DEFAULT ENCRYPTION='N' */;# 使用test数据库
USE `test`;--
-- Table structure for table `test`
--# test表如果存在,则删除test表
DROP TABLE IF EXISTS `test`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;# 创建表test
CREATE TABLE `test` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `test`
--# 在表test上加写锁
LOCK TABLES `test` WRITE;
/*!40000 ALTER TABLE `test` DISABLE KEYS */;# 插入数据
INSERT INTO `test` VALUES (1,'瓜田李下'),(2,'瓜田李下 2');
/*!40000 ALTER TABLE `test` ENABLE KEYS */;# 释放锁
UNLOCK TABLES;--
-- Table structure for table `test2`
--# 表test2如果存在,则删除表test2
DROP TABLE IF EXISTS `test2`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;# 创建表test2
CREATE TABLE `test2` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `test2`
--# 表test2上加写锁
LOCK TABLES `test2` WRITE;
/*!40000 ALTER TABLE `test2` DISABLE KEYS */;# 插入数据
INSERT INTO `test2` VALUES (1,'海贼王'),(2,'火影忍者');
/*!40000 ALTER TABLE `test2` ENABLE KEYS */;# 释放写锁
UNLOCK TABLES;--
-- Current Database: `test2`
--# 数据库test2如果不存在,则创建数据库
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `test2` /*!40100 DEFAULT CHARACTER SET utf8 */ /*!80016 DEFAULT ENCRYPTION='N' */;# 使用数据库test2
USE `test2`;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;-- Dump completed on 2021-05-28 17:01:29

mysqldump -u root -p test test test2 > test2.backup:备份数据库test下的表test、test2

root@7a72b2ffd688:/# mysqldump -u root -p test test test2 > test2.backup
Enter password:
root@7a72b2ffd688:/# cat test2.backup
-- MySQL dump 10.13  Distrib 8.0.25, for Linux (x86_64)
--
-- Host: localhost    Database: test
-- ------------------------------------------------------
-- Server version   8.0.25/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;--
-- Table structure for table `test`
--# 表test如果存在,则删除表
DROP TABLE IF EXISTS `test`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;# 创建表test
CREATE TABLE `test` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `test`
--# 表test上加写锁
LOCK TABLES `test` WRITE;
/*!40000 ALTER TABLE `test` DISABLE KEYS */;# 插入数据记录
INSERT INTO `test` VALUES (1,'瓜田李下'),(2,'瓜田李下 2');
/*!40000 ALTER TABLE `test` ENABLE KEYS */;# 释放写锁
UNLOCK TABLES;--
-- Table structure for table `test2`
--# 表test2如果存在,则删除表
DROP TABLE IF EXISTS `test2`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;# 创建表test2
CREATE TABLE `test2` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `test2`
--# 表test2上加写锁
LOCK TABLES `test2` WRITE;
/*!40000 ALTER TABLE `test2` DISABLE KEYS */;# 插入数据记录
INSERT INTO `test2` VALUES (1,'海贼王'),(2,'火影忍者');
/*!40000 ALTER TABLE `test2` ENABLE KEYS */;# 释放写锁
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;-- Dump completed on 2021-05-28 17:13:26

*************************

主从数据备份:主从同步只能做增量同步,历史数据需要先做备份

锁定主库(备份期间主库只能读,不能写)

mysql> flush tables with read lock;
Query OK, 0 rows affected (0.00 sec)mysql> insert into test.test(id,name) values(3,"gtlx3");
ERROR 1223 (HY000): Can't execute the query because you have a conflicting read lock
#由于在所有表上都加了读锁,插入数据记录报错

查询主库状态,记录binary log position、filename

mysql> show master status \G;
*************************** 1. row ***************************File: binlog.000004Position: 2345Binlog_Do_DB: Binlog_Ignore_DB:
Executed_Gtid_Set:
1 row in set (0.00 sec)

主库导出数据记录

[root@centos mysql]# ls
[root@centos mysql]# docker exec -it mysql /usr/bin/mysqldump -u root --password=123456 test > test2.backup
[root@centos mysql]# ls
test2.backup
[root@centos mysql]# cat test2.backup
mysqldump: [Warning] Using a password on the command line interface can be insecure.
-- MySQL dump 10.13  Distrib 8.0.25, for Linux (x86_64)
--
-- Host: localhost    Database: test
-- ------------------------------------------------------
-- Server version   8.0.25/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;--
-- Table structure for table `test`
--DROP TABLE IF EXISTS `test`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `test` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `test`
--LOCK TABLES `test` WRITE;
/*!40000 ALTER TABLE `test` DISABLE KEYS */;
INSERT INTO `test` VALUES (1,'瓜田李下'),(2,'瓜田李下 2');
/*!40000 ALTER TABLE `test` ENABLE KEYS */;
UNLOCK TABLES;--
-- Table structure for table `test2`
--DROP TABLE IF EXISTS `test2`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `test2` (`id` int NOT NULL AUTO_INCREMENT,`name` varchar(255) NOT NULL,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb3;
/*!40101 SET character_set_client = @saved_cs_client */;--
-- Dumping data for table `test2`
--LOCK TABLES `test2` WRITE;
/*!40000 ALTER TABLE `test2` DISABLE KEYS */;
INSERT INTO `test2` VALUES (1,'海贼王'),(2,'火影忍者');
/*!40000 ALTER TABLE `test2` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;-- Dump completed on 2021-05-28 17:33:23

从库导入数据记录

[root@centos mysql]# cat test2.backup | docker exec -i mysql2 /usr/bin/mysql -u root --password=123456 test
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@centos mysql]# cat test2.backup | docker exec -i mysql2 /usr/bin/mysql -u root --password=123456 lihu
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@centos mysql]# cat test2.backup | docker exec -i mysql2 /usr/bin/mysql -u root --password=123456 lihu2
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1049 (42000): Unknown database 'lihu2'

说明:主从数据库名称可为不同,但需要预先创建,如果不存在会报错

主从备份后,可释放主库的写锁

mysql> unlock tables;
Query OK, 0 rows affected (0.00 sec)

mysql 数据备份(mysqldump)相关推荐

  1. mysql数据备份mysqldump

    mysqldump命令导出数据库 备份数据库(推荐背下来) 语法: mysqldump -u 用户名 -p 数据库名 > 盘符:\路径\文件名.sql 案例(备份到当前位置):[位置可以写成D: ...

  2. MYSQL数据备份之mysqldump命令详解(附脚本定时备份)

    一.常见备份命令介绍 备份命令 备份速度 恢复速度 介绍 功能 一般用于 cp 快 快 物理备份.灵活性低 很弱 少量数据备份 mysqldump 慢 慢 逻辑备份.适用所有存储引擎 一般 中小型数据 ...

  3. mysql 数据备份

    一:IDE工具介绍 生产环境还是推荐使用mysql命令行, 但为了方便我们测试 可以使用IDE 工具. 掌握 测试+链接数据库. 新建库 新建表,新增字段+类型+约束 设计表:外键 新增查询 备份库. ...

  4. MySQL数据备份命令

    MySQL数据备份命令 一.备份命令 1.备份命令 2.备份压缩 3.备份同个库多个表 4.同时备份多个库 5.备份实例上所有的数据库 6.备份数据出带删除数据库或者表的sql备份 7.备份数据库结构 ...

  5. MySQL数据备份、恢复

    文章目录 一.MySQL日志管理 1.1日志分类 1.2日志配置 1.3日志查询 二.MySQL数据备份 2.1物理备份 2.2逻辑备份 三.常用的备份方法 3.1物理冷备 3.2工具备份(温备) 3 ...

  6. mysql数据备份恢复

    数据备份恢复 一.概述 MySQL数据备份即databases Binlog my.cnf 所有备份数据都应放在非数据库本地,而且建议有多份副本.测试环境中做日常恢复演练,恢复较备份更为重要. 备份: ...

  7. MySQL数据备份恢复全攻略,让我们通过简单几步找回丢失的数据

    编写初衷 没有人生下来天生就是会计算机的,就拿笔者来说的话,也是从Windows->Centos->Ubuntu一步一步慢慢学习,积累下来的.为了让大家能够更快更高效率的学习,从今天开始, ...

  8. MySQL数据备份与SQL语句

    MySQL数据备份与SQL语句 1.mysql数据库备份与恢复 1.1 数据库常用备份方案 数据库备份方案: 全量备份 增量备份 差异备份 备份方案 特点 全量备份 全量备份就是指对某一个时间点上的所 ...

  9. Docker下Mysql数据备份

    Mysql数据备份 温馨提示 :本篇文章内容 手动备份 1.进到docker-compose配置文件所在目录 cd /root/apps/data-input-sy 2.查看所有镜像 docker-c ...

最新文章

  1. selenium+python headless 爬虫环境配置
  2. Windows 命令行输入输出重定向问题
  3. V-rep学习笔记:机器人逆运动学解算
  4. matlab元件阻感负载,单相桥式全控整流电路阻感负载课程设计matlab
  5. 《C++ Primer第五版》习题答案
  6. 有没有检查c语言编译错误的软件,求大佬解答,为什么这个程序编译软件检查不出错误...
  7. Java 输出当前目录
  8. 安全企业 Stormshield 披露数据泄露事件 源代码被盗
  9. HTML知识积累及实践(三) - 列表标签
  10. 禁用计算机服务,适当禁用系统服务 提升计算机运行速度
  11. 批处理禁用U盘,光驱,用户添加到组,盘符添加权限
  12. 用 Vue 做一个简单的购物app
  13. nod32/ESET下載及更新
  14. BLM战略规划的核心是业务模式创新
  15. uniapp button字体没有垂直居中
  16. kubernetes pod NodeLost 分析
  17. 隧道测量快速坐标反程序48004850计算器
  18. linux服务器503怎么解决,宝塔linux面板apache网站访问报错503 Service Unavailable怎么解决...
  19. 人工智能时代是什么时代?
  20. 鼠标悬浮触发事件(onmouseover)实现

热门文章

  1. android toast样式 最新,7个最好的Android本机Toast通知替换库
  2. 电脑开机一两秒就断电怎么办?
  3. SABSA企业安全架构-白皮书
  4. FLV:适合录制的多媒体格式
  5. 德迅游戏盾的妙用,分钟级集成,无视任何攻击
  6. 【高等数学】反常积分敛散性的判定工具——P积分的敛散性
  7. 删库跑路 mini 版!程序员写代码给自己转账21 万!判了~
  8. jdk11+Tomcat9配置
  9. 职业规划指导:消化这些技巧能让你升值一倍!!!
  10. 安装了MathType但Word中公式打不开