目录
数据库备份,数据库为school,素材如下
一、创建student和score表
sql
CREATE TABLE student (
id INT(10) NOT NULL UNIQUE PRIMARY KEY ,
name VARCHAR(20) NOT NULL ,
sex VARCHAR(4) ,
birth YEAR,
department VARCHAR(20) ,
address VARCHAR(50)
);
sql
CREATE TABLE score (
id INT(10) NOT NULL UNIQUE PRIMARY KEY AUTO_INCREMENT ,
stu_id INT(10) NOT NULL ,
c_name VARCHAR(20) ,
grade INT(10)
);
二、为student表和score表增加记录
sql
INSERT INTO student VALUES( 901,'张老大', '男',1985,'计算机系', '北京市海淀区');
INSERT INTO student VALUES( 902,'张老二', '男',1986,'中文系', '北京市昌平区');
INSERT INTO student VALUES( 903,'张三', '女',1990,'中文系', '湖南省永州市');
INSERT INTO student VALUES( 904,'李四', '男',1990,'英语系', '辽宁省阜新市');
INSERT INTO student VALUES( 905,'王五', '女',1991,'英语系', '福建省厦门市');
INSERT INTO student VALUES( 906,'王六', '男',1988,'计算机系', '湖南省衡阳市');
sql
INSERT INTO score VALUES(NULL,901, '计算机',98);
INSERT INTO score VALUES(NULL,901, '英语', 80);
INSERT INTO score VALUES(NULL,902, '计算机',65);
INSERT INTO score VALUES(NULL,902, '中文',88);
INSERT INTO score VALUES(NULL,903, '中文',95);
INSERT INTO score VALUES(NULL,904, '计算机',70);
INSERT INTO score VALUES(NULL,904, '英语',92);
INSERT INTO score VALUES(NULL,905, '英语',94);
INSERT INTO score VALUES(NULL,906, '计算机',90);
INSERT INTO score VALUES(NULL,906, '英语',85);
三、练习题
1.备份数据库school到/backup目录
[root@localhost ~]# mysqldump -u root -p123 school > /backup/school
2.备份MySQL数据库为带删除表的格式,能够让该备份覆盖已有数据库而不需要手动删除原有数据库
[root@localhost ~]# mysqldump -u root -p --add-drop-table school > /backup/sch1.sql
3.直接将MySQL数据库压缩备份
[root@localhost ~]# mysqldump -u root -p123 school | gzip > /backup/sch.sql.gz
4.备份MySQL数据库某个(些)表。此例备份student表
[root@localhost ~]# mysqldump -u root -p123 school student > /backup/stu
5.同时备份多个MySQL数据库(其他数据库素材自行准备)yyu
[root@localhost ~]# mysqldump -u root -p123 --databases school emp > /backup/two
6.仅仅备份数据库结构
[root@localhost ~]# mysqldump -u root -p123 --no-data school > /backup/nodata
7.备份服务器上所有数据库
[root@localhost ~]# mysqldump -uroot -p123 -A > /backup/all
8.还原MySQL数据库
mysql> drop database school;
[root@localhost ~]# mysql -uroot -p123 school < /backup/school
9.还原压缩的MySQL数据库
[root@localhost backup]# gunzip < sch.sql.gz | mysql -u root -p密码 school
10.使用xtrabackup 备份数据库
[root@localhost ~]# innobackupex --user=root --password=Fmx1220. /backup/test
11.在另外的数据库服务器上还原xtrabackup 备份
[root@localhost ~]# innobackupex --apply-log /backup/test/2023-07-21_14-29-08/
[root@localhost ~]# systemctl stop mysqld
[root@localhost ~]# rm -rf /var/lib/mysql/*
[root@localhost ~]# innobackupex --apply-log /backup/test/2023-07-21_14-29-08/
[root@localhost ~]# chown -R mysql:mysql /var/lib/mysql
[root@localhost ~]# systemctl restart mysqld
12.使用mydumper备份数据库
[root@localhost ~]# mydumper -u root -p123 -B school -o /backup/myschool
13.使用mydumper恢复数据库
mysql> drop database school;
[root@localhost ~]# myloader -u root -p123 -d /backup/myschool/ -o -B school