例题:数据库备份
1.创建student和score表
mysql> 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)
-> );
mysql> 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)
-> );
2.为student表和score表增加记录
向student表插入记录的INSERT语句如下:
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,'计算机系', '湖南省衡阳市');
向score表插入记录的INSERT语句如下:
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);
3. 备份数据库school到/backup目录
[root@localhost backup]# mysqldump -uroot -p --default-character-set=utf8 --set-gtid-purged=OFF -B --databases mysql Student > /backup/student.sql
4.备份MySQL数据库为带删除表的格式,能够让该备份覆盖已有数据库而不需要手动删除原有数据库
[root@localhost backup]# mysqldump --add-drop-table -uroot -p --default-character-set=utf8 --set-gtid-purged=OFF mysql student > /backup/school2.sql
5.直接将MySQL数据库压缩备份
[root@localhost backup]# mysqldump -uroot -p --default-character-set=utf8 --set-gtid-purged=OFF -B mysql | gzip > /backup/school.sql.gz
6.备份MySQL数据库某个(些)表。此例备份student表
[root@localhost backup]# mysqldump --add-drop-table -uroot -p --default-character-set=utf8 --set-gtid-purged=OFF mysql student > /backup/school2.sql
7.同时备份多个MySQL数据库(其他数据库素材自行准备)
查询数据库,备份多个数据库
[root@localhost backup]# mysqldump -uroot -p --default-character-set=utf8 --set-gtid-purged=OFF -B mysql db3 > /backup/school3.sql
8.仅仅备份数据库结构
[root@localhost backup]# mysqldump --no-data -uroot -p --default-character-set=utf8 --set-gtid-purged=OFF -B mysql > /backup/school4.sql
9.备份服务器上所有数据库
[root@localhost backup]# mysqldump --all-databases -uroot -p --default-character-set=utf8 --set-gtid-purged=OFF -B mysql > /backup/school5.sql
还原
1. source
mysql> source /backup/school2.sql
2.建一个新数据库test,放入备份数据后查看
[root@localhost backup]# mysql -uroot -p test < /backup/school1.sql
### 数据库备份还原操作成功###