使用CMD命令行来对MySQL数据库执行迁移、备份、恢复

时间:2022-02-27 10:35:56
1. 导出数据库数据
  "C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe" -u root -p123abc test > D:\Backup\MySQL\test_20140521.sql 
2. 将导出的数据dumpout.sql放到你的目标机器上(如果是远程目标机器的话,直接将dunmpout.sql copy到目标机器就行)。这里假设cp到主目录下~/
3. 在目标机器的数据库里建立新数据库,这里建立名为dp_db_bak的数据库
   mysql> create database dp_db_bak
4. 向dp_db_bak数据库导入数据
   mysql -uroot -p dp_db_bak < ~/dumpout.sql
   其中 root是账户名
        db_db_bak是新数据库
        ~/dumpout.sql是第一步导出的数据
P.S. 如果在导入导出数据的时候遇到文件太大异常退出的情况,可使用split/cat来进行文件的分割和合并
   mysqldump -uroot -p dp_db | split -b 10m - tempfile
   cat all_tempfile > targetfile
其他方法:

Mysql source命令在导入大数据时显得非常有用。虽然Mysql Administrator软件也不错,但就稳定性和效率性来说还是source占优。
使用方法:
Windows下将sql数据库备份拷贝到磁盘目录如:D:\db.sql,cmd进入命令行。
1、先使用命令mysql -uroot -p登陆mysql服务器
2、然后执行相关命令导入数据。

mysql> use dbtest; //设置当前要导入数据的dbtest数据库 
mysql> set names utf8; //设置编码 
mysql> source D:\db.sql; //导入数据

ok,完成。当然数据库备份用Mysql Administrator是非常方便的

1. CMD - MySQL Backup
"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe" -u root -p123abc test > D:\Backup\MySQL\test_20140521.sql 
可以通过计划任务来调用MySQL_Backup.bat批处理来实现每天自动备份;
@ECHO OFF
set y=�te:~0,4%
set m=�te:~5,2%
set d=�te:~8,2%
"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe" -u root -p123abc test > D:\Backup\MySQL\test_%y%%m%%d%.sql
2. CMD - MySQL Restore
恢复的过程,先创建一个数据库,然后进入这个数据库,使用Source来恢复数据库。
mysql.exe -u root -p
show databases;

create database test001;

use test001;   
source D:\Backup\MySQL\test_20140521.sql ; 
3. Example
### 备份
C:\Users\Administrator>"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysqldump.exe" -u root -p1234-qwer test > D:\Backup\MySQL\test_20140521.sql
Warning: Using a password on the command line interface can be insecure.
### 恢复
C:\Program Files\MySQL\MySQL Server 5.6\bin>mysql.exe -u root -p
Enter password: *********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 60
Server version: 5.6.10 MySQL Community Server (GPL)
Copyright (c) 2000, 2013, 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> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| test |
| world |
+--------------------+
7 rows in set (0.00 sec)
mysql> create database test001;
Query OK, 1 row affected (0.00 sec)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sakila |
| test |
| test001 |
| world |
+--------------------+
8 rows in set (0.00 sec)
mysql> use test001
Database changed
m