Copia de seguridad y recuperación de la base de datos MySQL (2): use el comando mysqldump (espera activa)

Copia de seguridad y recuperación de la base de datos MySQL (2): use el comando mysqldump (espera activa)

En el mantenimiento diario de la base de datos, a menudo es necesario exportar datos, mysqldump es una herramienta de exportación de datos que viene con MySQL y tiene funciones muy poderosas. El comando mysqldump puede cargar toda la base de datos en un solo archivo de texto. Este archivo de texto contiene todos los comandos SQL necesarios para reconstruir la base de datos. Este comando obtiene todo el esquema (Schema) y lo convierte en sintaxis DDL (instrucción CREATE, es decir, instrucción de definición de base de datos), obtiene todos los datos y crea una instrucción INSERT a partir de estos datos. mysqldump invierte todos los diseños de la base de datos.

La sintaxis del comando es la siguiente:

mysqldump [options] [db_name [tbl_name ...]] > file_name

Descripción:
(1) El archivo de texto exportado contiene el siguiente contenido: crear sentencia de juicio de base de datos -> eliminar tabla -> crear tabla -> bloquear tabla -> deshabilitar índice -> insertar datos -> habilitar índice -> desbloquear tabla;
(2) opciones Especifique el nombre de usuario, contraseña y otros parámetros para la operación;
(3) Especifique la base de datos y la tabla a exportar.

1. Exportar todas las bases de datos

(1) Utilice el parámetro -todas las bases de datos o -A para exportar todas las bases de datos y datos, incluidas las bases de datos del sistema.

###使用 --all-databases, -A 参数
[root@Mysql11 ~]# mysqldump -uroot -p -A > /tmp/all.sql
Enter password: 
[root@Mysql11 ~]# 

(2) Utilice el parámetro -add-drop-database para agregar la declaración de eliminación de la base de datos antes de que se cree cada base de datos

[root@Mysql11 ~]# mysqldump -uroot -p -A --add-drop-database > /tmp/all.sql
Enter password: 

(3) Use el parámetro -add-drop-table para agregar una declaración de eliminación de tabla de datos antes de que se cree cada tabla de datos (este parámetro está activado de forma predeterminada y use -skip-add-drop-table para cancelar la opción)

[root@Mysql11 ~]# mysqldump -uroot -p -A --skip-add-drop-database --skip-add-drop-table > /tmp/all.sql
Enter password: 

Dos, exportar una o más bases de datos

Utilice el parámetro –databases db1 db2… para especificar el nombre de la base de datos que se va a exportar, como exportar todos los datos de las bases de datos wgx e hist:

[root@Mysql11 ~]# mysqldump -uroot -p --databases wgx hist > /tmp/d1d2.sql
Enter password: 

Exporta todos los datos en la base de datos wgx:

[root@Mysql11 ~]# mysqldump -uroot -p --databases wgx > /tmp/wgx.sql
Enter password: 

Vea el contenido del archivo wgx de la siguiente manera:

[root@Mysql11 ~]# cat /tmp/wgx.sql
-- MySQL dump 10.13  Distrib 5.7.27, for Linux (x86_64)
--
-- Host: localhost    Database: wgx
-- ------------------------------------------------------
-- Server version	5.7.27

/*!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 */;
/*!40101 SET NAMES utf8 */;
/*!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: `wgx`
--

###############   创建数据库wgx   ############################################################
CREATE DATABASE /*!32312 IF NOT EXISTS*/ `wgx` /*!40100 DEFAULT CHARACTER SET utf8 */;
############################################################################################
USE `wgx`;

--
-- Table structure for table `department`
--

################  创建表department  ########################################################
DROP TABLE IF EXISTS `department`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `department` (
  `dept_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) DEFAULT NULL,
  PRIMARY KEY (`dept_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
############################################################################################
--
-- Dumping data for table `department`
--

################  锁表  ####################################################################
LOCK TABLES `department` WRITE;
############################################################################################
/*!40000 ALTER TABLE `department` DISABLE KEYS */;

################  向表department中插入数据   #################################################
INSERT INTO `department` VALUES (1,'guanli'),(2,'jingji'),(3,'jidian'),(4,'jisuanji');
############################################################################################
/*!40000 ALTER TABLE `department` ENABLE KEYS */;

################  解锁  ####################################################################
UNLOCK TABLES;
############################################################################################
--
-- Table structure for table `emp`
--

DROP TABLE IF EXISTS `emp`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `emp` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(20) DEFAULT NULL,
  `phone` char(11) DEFAULT NULL,
  `dept_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `emp`
--

LOCK TABLES `emp` WRITE;
/*!40000 ALTER TABLE `emp` DISABLE KEYS */;
INSERT INTO `emp` VALUES (1,'zhangsan',20,'Xinxiang','15578941258',1),(2,'tom',20,'Xinxiang','13778942222',1),(3,'jack',20,'Zhengzhou','13675871454',1),(4,'john',21,'Zhengzhou','13937681111',2),(5,'mark',22,'Aanyang','13055882233',2);
/*!40000 ALTER TABLE `emp` 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 2020-07-01 22:31:19

Tres, exportar una tabla especificada en una base de datos

Utilice –database para especificar la base de datos y el parámetro –tables para especificar la tabla, la sintaxis es la siguiente:

[root@Mysql11 ~]# mysqldump -uroot -p --databases 数据库名 --tables table1 table2 > /tmp/wgx.sql

Nota: La exportación de una tabla específica en una base de datos solo se puede exportar para una base de datos, y el contenido exportado es diferente de exportar la base de datos completa. No hay una sentencia de juicio para crear una base de datos en el texto de exportación de la tabla especificada, solo elimine la creación de tabla Datos de importación de tabla.

(1) Exportar las tablas dept y stu:

[root@Mysql11 ~]# mysqldump -uroot -p --databases hist --tables dept stu > /tmp/wgx.sql
Enter password: 

Exportar la tabla stu:

[root@Mysql11 ~]# mysqldump -uroot -p --databases hist --tables stu > /tmp/stu.sql
Enter password: 

Vea el contenido del archivo stu.sql:

[root@Mysql11 ~]# cat /tmp/stu.sql
-- MySQL dump 10.13  Distrib 5.7.27, for Linux (x86_64)
--
-- Host: localhost    Database: hist
-- ------------------------------------------------------
-- Server version	5.7.27

/*!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 */;
/*!40101 SET NAMES utf8 */;
/*!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 `stu`
--

DROP TABLE IF EXISTS `stu`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `stu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(20) DEFAULT NULL,
  `phone` char(11) DEFAULT NULL,
  `dept_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `stu`
--

LOCK TABLES `stu` WRITE;
/*!40000 ALTER TABLE `stu` DISABLE KEYS */;
INSERT INTO `stu` VALUES (1,'zhangsan',20,'Xinxiang','15578941258',1),(2,'tom',20,'Xinxiang','13778942222',1),(3,'jack',20,'Zhengzhou','13675871454',1),(4,'john',21,'Zhengzhou','13937681111',2),(5,'mark',22,'Aanyang','13055882233',2);
/*!40000 ALTER TABLE `stu` 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 2020-07-01 22:48:07

Cuarto, los registros de la tabla de exportación que cumplen las condiciones especificadas.

Utilice –where para especificar las condiciones de exportación, por ejemplo: exporte el registro con dept_id 1 en la tabla stu:

[root@Mysql11 ~]# mysqldump -uroot -p --databases hist --tables stu --where='dept_id=1 > /tmp/stu.sql
Enter password: 
[root@Mysql11 ~]# 
[root@Mysql11 ~]# cat /tmp/stu.sql
-- MySQL dump 10.13  Distrib 5.7.27, for Linux (x86_64)
--
-- Host: localhost    Database: hist
-- ------------------------------------------------------
-- Server version	5.7.27

/*!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 */;
/*!40101 SET NAMES utf8 */;
/*!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 `stu`
--

DROP TABLE IF EXISTS `stu`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
####  创建表
CREATE TABLE `stu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(20) DEFAULT NULL,
  `phone` char(11) DEFAULT NULL,
  `dept_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `stu`
--
-- WHERE:  dept_id=1
####  锁表
LOCK TABLES `stu` WRITE;
/*!40000 ALTER TABLE `stu` DISABLE KEYS */;
###  插入数据
INSERT INTO `stu` VALUES (1,'zhangsan',20,'Xinxiang','15578941258',1),(2,'tom',20,'Xinxiang','13778942222',1),(3,'jack',20,'Zhengzhou','13675871454',1);
/*!40000 ALTER TABLE `stu` 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 2020-07-01 22:56:16

Exporte los datos del estudiante llamados 'jack' en la tabla stu:

[root@Mysql11 ~]# mysqldump -uroot -p --databases hist --tables stu --where="name='jack'" > /tmp/stu.sql
Enter password: 
[root@Mysql11 ~]# 
[root@Mysql11 ~]# cat /tmp/stu.sql
-- MySQL dump 10.13  Distrib 5.7.27, for Linux (x86_64)
--
-- Host: localhost    Database: hist
-- ------------------------------------------------------
-- Server version	5.7.27

/*!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 */;
/*!40101 SET NAMES utf8 */;
/*!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 `stu`
--

DROP TABLE IF EXISTS `stu`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `stu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(20) DEFAULT NULL,
  `phone` char(11) DEFAULT NULL,
  `dept_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `stu`
--
-- WHERE:  name='jack'

LOCK TABLES `stu` WRITE;
/*!40000 ALTER TABLE `stu` DISABLE KEYS */;
INSERT INTO `stu` VALUES (3,'jack',20,'Zhengzhou','13675871454',1);
/*!40000 ALTER TABLE `stu` 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 2020-07-01 22:58:07

Cinco, solo exporte la estructura de la tabla sin exportar datos

Utilice el parámetro -no-data para exportar solo la estructura de la tabla, de la siguiente manera:

[root@Mysql11 ~]# mysqldump -uroot -p --databases hist --tables stu --no-data > /tmp/stu.sql
Enter password: 
[root@Mysql11 ~]# cat /tmp/stu.sql
-- MySQL dump 10.13  Distrib 5.7.27, for Linux (x86_64)
--
-- Host: localhost    Database: hist
-- ------------------------------------------------------
-- Server version	5.7.27

/*!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 */;
/*!40101 SET NAMES utf8 */;
/*!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 `stu`
--

DROP TABLE IF EXISTS `stu`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `stu` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(20) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `address` varchar(20) DEFAULT NULL,
  `phone` char(11) DEFAULT NULL,
  `dept_id` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;
/*!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 2020-07-01 23:04:42

Seis, genera un nuevo archivo binlog

Utilice el parámetro -F para generar un nuevo archivo binlog después de exportar los datos.

[root@Mysql11 ~]# mysqldump -uroot -p --databases wgx -F >/tmp/wgx.sql
Enter password: 

Siete, exportar procedimientos almacenados y funciones personalizadas

Utilice el parámetro -routines o -R para exportar procedimientos almacenados y funciones personalizadas en la base de datos al mismo tiempo:

[root@Mysql11 ~]# mysqldump -uroot -p --databases wgx --routines > /tmp/wgx.sql
Enter password: 

8. Asegurar el estado consistente de la exportación.

Utilice el parámetro -single-transaction para enviar una instrucción BEGIN SQL antes de exportar los datos. BEGIN no bloqueará ninguna aplicación y puede garantizar el estado coherente de la base de datos al exportar. Solo se aplica al motor de almacenamiento InnoDB. Esta opción y la opción -lock-tables son mutuamente excluyentes, porque LOCK TABLES confirmará implícitamente cualquier transacción pendiente.

[root@Mysql11 ~]# mysqldump -uroot -p --databases wgx --single-transaction > /tmp/wgx.sql
Enter password: 

Nueve, importa los datos de respaldo

mysql -uroot -p  <  stu.sql

Supongo que te gusta

Origin blog.csdn.net/weixin_44377973/article/details/107074410
Recomendado
Clasificación