1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Amazon RDS for MySQL同士でデータコピー(シェルスクリプト)

Last updated at Posted at 2018-04-18

前提

**"Amazon RDS for MySQL"**インスタンス2台
mysql1, mysql2と表記)

mysql1とmysql2でテーブル定義が同じであるようなテーブル(1GB程度)が複数ある。
例えば、ステージング環境と本番環境。

シェルスクリプトを動かすEC2 1台用意済みとする。

やりたいこと

mysql1からmysql2へ下記5テーブルをコピーしたい。

  • table_name1
  • table_name2
  • table_name3
  • table_name4
  • table_name5

コード

対象テーブルのDB名はmysql1もmysql2も共通で、db_nameとした場合。

table_copy.sh
#!/bin/bash
function tablecp {
    # CSVファイル削除
    rm -f data_$1.csv
    # CSVファイルにエクスポート
    mysql -h mysql1.**************.ap-northeast-1.rds.amazonaws.com -P 3306 -u root db_name -e "SELECT * FROM $1"  | sed -e 's/^/"/g' | sed -e 's/$/"/g' | sed -e 's/\t/","/g' | sed -e 's/"NULL"/NULL/g' > data_$1.csv
    # テーブルを空にする
    mysql -h mysql2.**************.ap-northeast-1.rds.amazonaws.com -P 3306 -u root db_name -e "truncate table $1"
    # CSVファイルをインポート
    mysql -h mysql2.**************.ap-northeast-1.rds.amazonaws.com -P 3306 -u root db_name -e "LOAD DATA LOCAL INFILE 'data_$1.csv' INTO TABLE $1 FIELDS TERMINATED BY ',' ENCLOSED BY '\"' LINES TERMINATED BY '\n' IGNORE 1 LINES;"
    # CSVファイル削除
    rm -f data_$1.csv
}

tablecp table_name1
tablecp table_name2
tablecp table_name3
tablecp table_name4
tablecp table_name5
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?