当前位置:网站首页>MySQL backup and restore single database and single table

MySQL backup and restore single database and single table

2022-07-01 15:30:00 zsk_ john

MySQL Backup and recovery of database is one of the basic operations , This article makes a detailed summary of this .

One ,MySQL Introduction to login ( The prerequisite for backup and recovery is to log in MySQL The server , therefore , It should be introduced )

MySQL There are several login methods :

(1), Command line (Windows To call down cmd) Sign in

MySQL Command line login , Mainly mysql -hip -P port -uroot -p   Here we need to pay attention to the following :

If it's the default 3306 port ,-P It can be omitted , Not 3306 Port must be specified .

If it's a local login ,-h Parameters can also be omitted . Non local login , Login must be specified ip.

-p (- Small p) This parameter specifies the password , It is generally not recommended to put the password after the parameter , For the security of the server .

Parameters can be followed by spaces or no spaces , Usually for the sake of beauty , It is not recommended to add spaces . such as , Here's an example , I am logged in to 192.168.0.17 On the server MySQL service .-u root There are spaces here , But you can also leave blank

[[email protected] ~]# mysql -h192.168.0.17 -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.23-log MySQL Community Server (GPL)

Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> ^DBye

(2), Database graphical management tools (navicat,sqlyog,MySQL Workbench,MySQL ODBC Connector,phpMyAdmin Wait for tools )

Graphical management tools are usually installed in Windows Under the system , Just because Linux Generally, graphical interfaces are not installed , and MySQL Usually installed in Linux Under the system , therefore ,MySQL The database must and should be able to provide remote access . such as ,navicat Remote access to :

(3),MySQL The client of  (Linux Generally, installation is not required MySQL Client's , The command line is enough , This means Windows Systematic MySQL client )

å¨è¿éæå¥å¾çæè¿°

Two , SQL Types of documents

Many students may have questions ,SQL Are there any other kinds of documents ? Yes , Yes mysqldump The program is backed up SQL file , There are also separate databases and tables SQL file , Like the following dump file :

-- MySQL dump 10.13  Distrib 5.7.23, for linux-glibc2.12 (x86_64)
--
-- Host: 192.168.0.17    Database: emp
-- ------------------------------------------------------
-- Server version	5.7.23-log

/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @[email protected]@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
........ Slightly 

In this way SQL Script to build table SQL file ;

create table  if not exists DEPT
(
    DEPTNO int(2) not null,
    DNAME varchar(14),
    LOC varchar(13)
);
 
alter table DEPT add constraint PK_DEPT primary key (DEPTNO);
 
create table if not exists EMP
(
    EMPNO int(4) not null,
    ENAME varchar(10),
    JOB varchar(9),
    MGR int(4),
    HIREDATE date,
    SAL int(7 ),
    COMM int(7 ),
    DEPTNO int(2)
);
 
alter table EMP add constraint PK_EMP primary key (EMPNO);
alter table EMP add constraint FK_DEPTNO foreign key (DEPTNO) references DEPT (DEPTNO);

 
insert into DEPT (DEPTNO, DNAME, LOC) values (10, 'ACCOUNTING', 'NEW YORK');
insert into DEPT (DEPTNO, DNAME, LOC) values (20, 'RESEARCH', 'DALLAS');
insert into DEPT (DEPTNO, DNAME, LOC) values (30, 'SALES', 'CHICAGO');
insert into DEPT (DEPTNO, DNAME, LOC) values (40, 'OPERATIONS', 'BOSTON');
 
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO) values (7369, 'SMITH', 'CLERK', 7902, str_to_date('17 12 1980', '%d %m %Y'), 800,null,20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7499, 'ALLEN', 'SALESMAN', 7698, str_to_date('20 02 1981', '%d %m %Y'),1600, 300, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7521, 'WARD', 'SALESMAN', 7698, str_to_date('22 02 1981', '%d %m %Y'),1250, 500, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7566, 'JONES', 'MANAGER', 7839, str_to_date('02 04 1981', '%d %m %Y'),2975, null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7654, 'MARTIN', 'SALESMAN', 7698, str_to_date('28 09 1981', '%d %m %Y'),1250, 1400, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7698, 'BLAKE', 'MANAGER', 7839, str_to_date('01 05 1981', '%d %m %Y'),2850, null, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7782, 'CLARK', 'MANAGER', 7839, str_to_date('09 06 1981', '%d %m %Y'),2450, null, 10);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7788, 'SCOTT', 'ANALYST', 7566, str_to_date('19 04 1987', '%d %m %Y'),3000,null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7839, 'KING', 'PRESIDENT', null, str_to_date('17 11 1981', '%d %m %Y'),5000,null, 10);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7844, 'TURNER', 'SALESMAN', 7698, str_to_date('08 09 1981', '%d %m %Y'),1500, 0, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7876, 'ADAMS', 'CLERK', 7788, str_to_date('23 05 1987', '%d %m %Y'),1100,null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7900, 'JAMES', 'CLERK', 7698, str_to_date('03 12 1981', '%d %m %Y'),950,null, 30);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7902, 'FORD', 'ANALYST', 7566, str_to_date('03 12 1981', '%d %m %Y'),3000,null, 20);
insert into EMP (EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO)values (7934, 'MILLER', 'CLERK', 7782, str_to_date('23 01 1982', '%d %m %Y'),1300,null, 10);
 
 
create table  if not exists salgrade (
    grade numeric primary key,
    losal numeric,
    hisal numeric
);
 
insert into salgrade values (1, 700, 1200);
insert into salgrade values (2, 1201, 1400);
insert into salgrade values (3, 1401, 2000);
insert into salgrade values (4, 2001, 3000);
insert into salgrade values (5, 3001, 9999);

3、 ... and ,mysqldump Backup

MySQLdump Backup only verifies the password for security purposes root password , This command specifies the required backup range through different parameter combinations .

The detailed meanings of the main parameters are as follows :

 -A --all-databases: Export all databases 
 2 -Y --all-tablespaces: Export all tablespaces 
 3 -y --no-tablespaces: Do not export any tablespace information 
 4 --add-drop-database Add... Before each database is created drop Database statement .
 5 --add-drop-table Add... Before each data table is created drop Data table statements .( The default is on , Use --skip-add-drop-table Cancel options )
 6 --add-locks Add... Before each table export LOCK TABLES And then UNLOCK TABLE.( The default is on , Use --skip-add-locks Cancel options )
 7 --comments Additional notes . It is on by default , It can be used --skip-comments Cancel 
 8 --compact Export less output information ( For debugging ). Get rid of the comments and the head and tail structures . Options available :--skip-add-drop-table --skip-add-locks --skip-comments --skip-disable-keys
 9 -c --complete-insert: Use the complete insert sentence ( Include column names ). This can improve insertion efficiency , But there may be max_allowed_packet The parameter causes the insert to fail .
10 -C --compress: Enable compression to pass all information between client and server 
11 -B--databases: Export several databases . All name parameters after the parameter are treated as database names .
12 --debug Output debug Information , For debugging . The default value is :d:t:o,/tmp/
13 --debug-info Output debugging information and exit 
14 --default-character-set Set default character set , The default value is utf8
15 --delayed-insert Delay insertion mode is adopted (INSERT DELAYED) Derived data 
16 -E--events: Export Events .
17 --master-data: When writing a backup to a backup file binlog file , Recovering into , Incremental data is recovered from the log after this file . The value is 1 when ,binlog There are no comments for the filename and location , by 2 when , In the backup file binlog The file name and location of the 
18 --flush-logs Refresh log before starting export . Please note that : If you export more than one database at a time ( Use options --databases perhaps --all-databases), The logs will be refreshed database by database . In addition to using --lock-all-tables perhaps --master-data Outside . under these circumstances , The log will be refreshed once , Accordingly, all tables are locked at the same time . therefore , If you plan to export and refresh logs at the same time, you should use --lock-all-tables  perhaps --master-data  and --flush-logs.
19 --flush-privileges Exporting mysql After database , Send out a FLUSH PRIVILEGES  sentence . In order to recover correctly , This option should be used to export mysql Databases and dependencies mysql Any time the database data .
20 --force Ignore the occurrence of SQL error .
21 -h --host: Host information to be exported 
22 --ignore-table Do not export the specified table . Specifies that when multiple tables are ignored , It needs to be repeated many times , One watch at a time . Each table must specify both the database and the table name . for example :--ignore-table=database.table1 --ignore-table=database.table2 ……
23 -x --lock-all-tables: Submit request to lock all tables in all databases , To ensure data consistency . This is a global read lock , And automatically turn off --single-transaction  and --lock-tables  Options .
24 -l --lock-tables: Before you start exporting , Lock all tables . use READ LOCAL Lock the table to allow MyISAM Table inserts in parallel . For tables that support transactions, for example InnoDB and BDB,--single-transaction It's a better choice , Because it doesn't need to lock the table at all . Note that when exporting multiple databases ,--lock-tables Lock tables for each database separately . therefore , This option does not guarantee the logical consistency of the tables in the export file between databases . The export status of different database tables can be completely different .
25 --single-transaction: fit innodb Backup of transaction database . Ensure the consistency of backup , The principle is to set the isolation level of this session to Repeatable read, To ensure that this conversation ( That is to say dump) when , No data submitted by other sessions will be seen .
26 -F: Refresh binlog, If binlog Open the ,-F Parameters are automatically refreshed during backup binlog Switch .
27 -n --no-create-db: Export data only , Without adding CREATE DATABASE  sentence .
28 -t --no-create-info: Export data only , Without adding CREATE TABLE  sentence .
29 -d --no-data: Don't export any data , Only export database table structure .
30 -p --password: Connection database password 
31 -P --port: Connection database port number 
32 -u --user: Specify the user name of the connection .
 Use... For example :


a、 Export the entire database ( Including the data in the database )
mysqldump -u username -p dbname > dbname.sql 
b、 Export database structure ( No data )
mysqldump -u username -p -d dbname > dbname.sql
c、 Export a data table in the database ( Include data )
mysqldump -u username -p dbname tablename > tablename.sql
d、 Export the table structure of a data table in the database ( No data )
mysqldump -u username -p -d dbname tablename > tablename.sql

such as , The full database backup command is ;

[[email protected] ~]# mysqldump -uroot -p -h192.168.0.17 -A >alll.sql
Enter password:
 Enter the correct password and start backing up the database , When backing up the database, the table and database will be locked , Here we need to pay attention to .

[[email protected] ~]# ls -alh all.sql 
-rw-r--r-- 1 root root 793K Feb 13 16:54 all.sql

Back up the specified database, such as , I am here 192.168.0.17 The database on this server has test database , I want to back up test and mysql These two databases , that , The order should be as follows :

[[email protected] ~]# mysqldump -uroot -p -h192.168.0.17 test EMP DEPT >empdept.sql
Enter password: 

 You can't add... At this time -B Parameters , The first parameter only writes the database name , Followed by the name of the table you want to back up , Be careful , Table names are case sensitive 

  The contents of the backed up file are as follows :

[[email protected] ~]# cat empdept.sql 
-- MySQL dump 10.13  Distrib 5.7.23, for linux-glibc2.12 (x86_64)
--
-- Host: 192.168.0.17    Database: test
-- ------------------------------------------------------
-- Server version	5.7.23-log

/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */;
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */;
/*!40101 SET @[email protected]@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @[email protected]@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @[email protected]@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @[email protected]@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @[email protected]@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @[email protected]@SQL_NOTES, SQL_NOTES=0 */;

--
-- 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` (
  `EMPNO` int(4) NOT NULL,
  `ENAME` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL,
  `JOB` varchar(9) COLLATE utf8_unicode_ci DEFAULT NULL,
  `MGR` int(4) DEFAULT NULL,
  `HIREDATE` date DEFAULT NULL,
  `SAL` int(7) DEFAULT NULL,
  `COMM` int(7) DEFAULT NULL,
  `DEPTNO` int(2) DEFAULT NULL,
  PRIMARY KEY (`EMPNO`),
  KEY `FK_DEPTNO` (`DEPTNO`),
  CONSTRAINT `FK_DEPTNO` FOREIGN KEY (`DEPTNO`) REFERENCES `DEPT` (`DEPTNO`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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 (7369,'SMITH','CLERK',7902,'1980-12-17',800,NULL,20),(7499,'ALLEN','SALESMAN',7698,'1981-02-20',1600,300,30),(7521,'WARD','SALESMAN',7698,'1981-02-22',1250,500,30),(7566,'JONES','MANAGER',7839,'1981-04-02',2975,NULL,20),(7654,'MARTIN','SALESMAN',7698,'1981-09-28',1250,1400,30),(7698,'BLAKE','MANAGER',7839,'1981-05-01',2850,NULL,30),(7782,'CLARK','MANAGER',7839,'1981-06-09',2450,NULL,10),(7788,'SCOTT','ANALYST',7566,'1987-04-19',3000,NULL,20),(7839,'KING','PRESIDENT',NULL,'1981-11-17',5000,NULL,10),(7844,'TURNER','SALESMAN',7698,'1981-09-08',1500,0,30),(7876,'ADAMS','CLERK',7788,'1987-05-23',1100,NULL,20),(7900,'JAMES','CLERK',7698,'1981-12-03',950,NULL,30),(7902,'FORD','ANALYST',7566,'1981-12-03',3000,NULL,20),(7934,'MILLER','CLERK',7782,'1982-01-23',1300,NULL,10);
/*!40000 ALTER TABLE `EMP` ENABLE KEYS */;
UNLOCK TABLES;

--
-- 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` (
  `DEPTNO` int(2) NOT NULL,
  `DNAME` varchar(14) COLLATE utf8_unicode_ci DEFAULT NULL,
  `LOC` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`DEPTNO`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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 (10,'ACCOUNTING','NEW YORK'),(20,'RESEARCH','DALLAS'),(30,'SALES','CHICAGO'),(40,'OPERATIONS','BOSTON');
/*!40000 ALTER TABLE `DEPT` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET [email protected]_TIME_ZONE */;

/*!40101 SET [email protected]_SQL_MODE */;
/*!40014 SET [email protected]_FOREIGN_KEY_CHECKS */;
/*!40014 SET [email protected]_UNIQUE_CHECKS */;
/*!40101 SET [email protected]_CHARACTER_SET_CLIENT */;
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */;
/*!40101 SET [email protected]_COLLATION_CONNECTION */;
/*!40111 SET [email protected]_SQL_NOTES */;

-- Dump completed on 2022-02-15 21:36:30

  here , We should be able to see , Default dump The table will be locked during backup .----LOCK TABLES `DEPT` WRITE;

Recovery is relatively simple ,

mysql -uroot -p < Backed up files 
 Enter the correct password , You can recover , However, it is best to check whether there are database and table creation statements before recovery , without , Please add it yourself .

summary :

(1)
MySQLdump During the backup operation , added -B After the parameter , There are many backup files Create database and use database The order of 
 Add -B Benefits of parameters :
 add -B After the parameter , The statement to create and use the library already exists in the exported data file , There is no need to manually create a library in the original library , There is no need to manually build the database during the recovery process , Can restore recovery directly 

(2)

--compact: Remove comments from backup files , Suitable for debugging , Production scenario is not applicable 
-A: Back up all libraries --- This suggestion is to do this when there is enough disk space 
-F: Refresh binlog journal 
--master-data: Add... To the backup file binlog Log file name and corresponding location point 
-x  --lock-all-tables: Lock table 
-l: Read only lock table --- Keep the consistency of transactions 
-d: Back up table structure only --- This is usually not used 
-t: Backup data only --- There are only insert statements in the backed up file 
--single-transaction: fit innodb Backup of transaction database 
   InnoDB When the table is backed up , Usually the option is enabled --single-transaction To ensure the consistency of backup , The principle is to set the isolation level of this session to Repeatable read, To ensure that this conversation ( That is to say dump) when , No data submitted by other sessions will be seen .

(3)

-d Parameters , Back up table structure only 
mysqldump -uroot -p'123456' -d mytest stusent > /mnt/studentDesc_bak.sql

-t Parameters , Backup data only 
mysqldump -uroot -p'123456'  -t mytest stusent > /mnt/studentData_bak.sql

 

原网站

版权声明
本文为[zsk_ john]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202152353400793.html