Copia de seguridad y recuperación de la base de datos MySQL (3): restauración de datos

Copia de seguridad y recuperación de la base de datos MySQL (3): restauración de datos

Use la propia herramienta de respaldo de MySQL, mysqldump, para respaldar los datos y luego restaurarlos.

1. Realice una copia de seguridad de los datos en formato SQL y restaure

1. Realice una copia de seguridad de todas las bases de datos

[root@Mysql11 ~]# mysqldump -uroot -p123456 --all-databases > /tmp/all.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

2. Realice una copia de seguridad de varias bases de datos especificadas

[root@Mysql11 ~]# mysqldump -uroot -p123456 --databases wgx hist > /tmp/all.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

Restaurar bases de datos wgx e hist

Método 1: inicie sesión en mysql para la recuperación

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hist               |
| mysql              |
| performance_schema |
| sys                |
| wgx                |
+--------------------+
6 rows in set (0.00 sec)

mysql> drop database wgx;
Query OK, 2 rows affected (0.03 sec)

mysql> drop database hist;
Query OK, 2 rows affected (0.03 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
4 rows in set (0.00 sec)

mysql> source /tmp/all.sql;
Query OK, 0 rows affected (0.00 sec)
.....
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hist               |
| mysql              |
| performance_schema |
| sys                |
| wgx                |
+--------------------+
6 rows in set (0.00 sec)

Método 2: restaurar sin iniciar sesión en mysql

[root@Mysql11 ~]# mysql -uroot -p123456 -e "drop database wgx;drop database hist;"
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 ~]# mysql -uroot -p123456 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
+--------------------+

[root@Mysql11 ~]# mysql -uroot -p123456 < /tmp/all.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 ~]# mysql -uroot -p123456 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hist               |
| mysql              |
| performance_schema |
| sys                |
| wgx                |
+--------------------+

3. Realice una copia de seguridad de una base de datos específica

(1) Especifique el parámetro -databases

[root@Mysql11 ~]# mysqldump -uroot -p123456 --databases wgx > /tmp/wgx.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

El archivo de respaldo generado por este comando contiene los comandos de creación y uso de la base de datos, de la siguiente manera:

[root@Mysql11 ~]# cat /tmp/wgx.sql
--
-- Current Database: `wgx`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `wgx` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `wgx`;

(2) Tampoco puede especificar el parámetro -databases

[root@Mysql11 ~]# mysqldump -uroot -p123456 wgx > /tmp/wgx.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.

Al hacer una copia de seguridad de una base de datos, puede omitir el parámetro -databases, pero no hay ninguna instrucción CREATE DATABASE y USE en el archivo de copia de seguridad generado después de omitir este parámetro, luego, al restaurar el archivo de copia de seguridad, debe especificar un nombre de base de datos predeterminado.

Puede utilizar un nombre de base de datos diferente al nombre de la base de datos original.

[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 */;

--
-- Table structure for table `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 */;

4. Restaurar todos los datos en una base de datos

Método 1: si existe el parámetro –databases al realizar una copia de seguridad de la base de datos

[root@Mysql11 ~]# mysql -uroot -p123456 -e "drop database wgx;"
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 ~]# mysql -uroot -p123456 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hist               |
| mysql              |
| performance_schema |
| sys                |
+--------------------+
[root@Mysql11 ~]# mysql -uroot -p123456 < /tmp/wgx.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 ~]# mysql -uroot -p123456 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hist               |
| mysql              |
| performance_schema |
| sys                |
| wgx                |
+--------------------+

Método 2: si no hay un parámetro –databases al realizar una copia de seguridad de la base de datos

[root@Mysql11 ~]# mysql -uroot -p123456 < /tmp/wgx.sql
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1046 (3D000) at line 22: No database selected

Nota: Si no se selecciona ninguna base de datos, se producirá un error: ERROR 1046 (3D000) en la línea 22: No se seleccionó ninguna base de datos

Por lo tanto, primero debe usar el comando use para seleccionar la base de datos que se restaurará:

[root@Mysql11 ~]# mysql -uroot -p123456 -e "drop database wgx;create database wanggx;use wanggx;source /tmp/wgx.sql;"
mysql: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 ~]# mysql -uroot -p123456 -e "show databases;"
mysql: [Warning] Using a password on the command line interface can be insecure.
+--------------------+
| Database           |
+--------------------+
| information_schema |
| hist               |
| mysql              |
| performance_schema |
| sys                |
| wanggx             |

Como puede ver, el nombre de la base de datos se modificó al restaurar los datos.

5. Recuperar varias tablas en una base de datos

Método 1: especifique los parámetros –base de datos y –tables

[root@Mysql11 ~]# mysqldump -uroot -p123456 --databases hist --tables dept stu > hist.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 ~]# cat hist.sql
............
--
-- Table structure for table `dept`
--

DROP TABLE IF EXISTS `dept`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dept` (
  `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 `dept`
--

LOCK TABLES `dept` WRITE;
/*!40000 ALTER TABLE `dept` DISABLE KEYS */;
INSERT INTO `dept` VALUES (1,'guanli'),(2,'jingji'),(3,'jidian'),(4,'jisuanji');
/*!40000 ALTER TABLE `dept` ENABLE KEYS */;
UNLOCK TABLES;

--
-- 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 */;

...........

-- Dump completed on 2020-07-02 10:07:03

Método 2: no especifique el parámetro –databases

Si no especifica el parámetro -databases, el nombre predeterminado es el nombre de la base de datos y el resto de los nombres son nombres de tablas, en el siguiente formato:

mysqldump -uuser -p db_name t_name1 t_name2 > file_name

P.ej:

[root@Mysql11 ~]# mysqldump -uroot -p123456 hist dept stu > /tmp/hist-bak.sql
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 ~]# cat /tmp/hist-bak.sql
...............

--
-- Table structure for table `dept`
--

DROP TABLE IF EXISTS `dept`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dept` (
  `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 `dept`
--

LOCK TABLES `dept` WRITE;
/*!40000 ALTER TABLE `dept` DISABLE KEYS */;
INSERT INTO `dept` VALUES (1,'guanli'),(2,'jingji'),(3,'jidian'),(4,'jisuanji');
/*!40000 ALTER TABLE `dept` ENABLE KEYS */;
UNLOCK TABLES;

--
-- 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 */;

.................

-- Dump completed on 2020-07-02 10:10:24

2. La copia de seguridad está en un formato de archivo de texto delimitado y está restaurada.

1. Utilice el parámetro [–tab = directorio] para realizar una copia de seguridad

[root@Mysql11 tmp]# mysqldump -uroot -p123456 --tab=/tmp/ hist
mysqldump: [Warning] Using a password on the command line interface can be insecure.
[root@Mysql11 tmp]# ls
dept.sql  dept.txt  stu.sql  stu.txt

Al llamar a mysqldump, si se usa la opción -tab = dir_name para hacer una copia de seguridad de la base de datos, dir_name indica el directorio del archivo de salida. En este directorio, cada tabla a respaldar generará dos archivos, uno es un archivo sql, incluido CREATE Declaración TABLE; el otro es un archivo txt, cada fila del archivo es un registro en la tabla de datos, y el valor de la columna y el valor de la columna están separados por 'tabulación'.

El contenido del archivo dept.sql es el siguiente:

[root@Mysql11 tmp]# cat dept.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' */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `dept`
--

DROP TABLE IF EXISTS `dept`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dept` (
  `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 */;

/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!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-02 10:23:16
[root@Mysql11 tmp]# 

El contenido del archivo dept.txt es el siguiente:

[root@Mysql11 tmp]# cat dept.txt
1	guanli
2	jingji
3	jidian
4	jisuanji

2. Restaurar datos

Al recuperar datos, primero use el comando mysql para procesar el archivo .sql para restaurar la estructura de la tabla, y luego procese el archivo .txt para cargar el registro.

(1) Restaurar la estructura de la tabla

[root@Mysql11 tmp]# mysql -uroot -p123456 -e "use hist;source /tmp/dept.sql;"
mysql: [Warning] Using a password on the command line interface can be insecure.

También puede usar: mysql -u nombre de usuario -p nombre de la base de datos <nombre de la tabla.sql

[root@Mysql11 tmp]# mysql -uroot -p123456 hist < dept.sql
mysql: [Warning] Using a password on the command line interface can be insecure.

(2) Restaurar datos

[root@Mysql11 tmp]# mysqlimport -uroot -p123456 hist /tmp/dept.txt
mysqlimport: [Warning] Using a password on the command line interface can be insecure.
hist.dept: Records: 4  Deleted: 0  Skipped: 0  Warnings: 0

Utilice el comando LOAD DATA INFILE para restaurar el registro:

[root@Mysql11 tmp]# mysql -uroot -p123456 -e "use hist;load data infile '/tmp/dept.txt' into table dept;"
mysql: [Warning] Using a password on the command line interface can be insecure.

Tres, use el comando select ... into outfile para exportar datos y restaurar datos

1. Exportar datos

[root@Mysql11 tmp]# mysql -uroot -p123456 hist -e "select * from stu into outfile '/tmp/stu.txt' fields terminated by ',';"
mysql: [Warning] Using a password on the command line interface can be insecure.

[root@Mysql11 tmp]# cat /tmp/stu.txt
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

2. Restaurar datos

[root@Mysql11 tmp]# mysql -uroot -p123456 hist -e "load data infile '/tmp/stu.txt' into table stu fields terminated by ',';"
mysql: [Warning] Using a password on the command line interface can be insecure.

[root@Mysql11 tmp]# mysql -uroot -p123456 hist -e "select * from stu;" 
mysql: [Warning] Using a password on the command line interface can be insecure.
+----+----------+------+-----------+-------------+---------+
| id | name     | age  | address   | phone       | dept_id |
+----+----------+------+-----------+-------------+---------+
|  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 |
+----+----------+------+-----------+-------------+---------+

Supongo que te gusta

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