7-3.MySQLのデータベースの引っ越し(バックアップ&リストア)

2019年7月15日

MySQLのバックアップ、リストアやデータベースの引っ越しはとても簡単です。
一度経験すれば怖くはありません。本番開始前に必ずリハーサルすべきです。

目次

1.大まかな流れ

データベースを引っ越す流れは大まかに以下の手順で行います。

1)現データべ―スをバックアップする
2)新しいMySQLをインストールする
3)データベースを作成する
4)バックアップしておいたデータベースを落とし込む

スポンサードサーチ

2.引っ越しの手順

では実際の手順を説明していきます。

1)現データべ―スをバックアップする

コマンドプロンプトより以下のコマンドでバックアップします。

【形式】

mysqldump -u root -pパスワード データベース名 > バックアップファイル名

【実行例】

C:\BKUP>mysqldump -u root -p studydb > studydb_BKUP.sql
Enter password: *************

C:\BKUP>

 

2)新しいMySQLをインストールする

これは状況次第です。
既に新しい環境のMySQLがあればそれを使用します。

新たにインストールしたい場合は以下の記事を参考にしてください。

0-2.MySQLをインストールする。(バージョン8.0.15)

3)データベースを作成する

引っ越し先のMySQLにログインしてデータベースを作成します。

①まずセッション接続する

コマンドプロンプトより
mysql -u root -pパスワード

②データベースを作成する

mysql > create database studydb;

③セッション切断する

mysql >exit

C:\BKUP>mysql -u root -p
Enter password: *************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 19
Server version: 8.0.15 MySQL Community Server - GPL

Copyright (c) 2000, 2019, 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> CREATE DATABASE studydb;
Query OK, 1 row affected (0.27 sec)

mysql> exit
Bye

C:\BKUP>

 

4)バックアップしておいたデータベースを落とし込む

引っ越し先のMySQLがインストールされているサーバ上でコマンドプロンプトを起動します。
コマンドプロンプトより以下のコマンドで実行します。

【コマンド】

mysql -u root -pパスワード データベース名 < バックアップ.sql

【実行例】

C:\BKUP>mysql -u root -p studydb <studydb_BKUP.sql       ←【リストアしています】
Enter password: *************

C:\BKUP>mysql -u root -p                    ←【ここからリストアの確認を行っています】
Enter password: *************
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 21
Server version: 8.0.15 MySQL Community Server - GPL

Copyright (c) 2000, 2019, 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> USE studydb;
Database changed
mysql> SHOW TABLES;
+-------------------+
| Tables_in_studydb |
+-------------------+
| shouhinmast       |
| table01           |
| table02           |
+-------------------+
3 rows in set (0.00 sec)

mysql>

 

以上です。
バックアップは定期的に取っておくのはシステム運用においてテッパンです。
タスクスケジュールしておくとより安心ですね。