テスト環境
-
次のdocker-compose.ymlでMySQL5.7を立ち上げた後、
create_table.sql
でテーブルtest_table
を作成する。 -
docker-compose.yml
version: '3' services: # MySQL db: image: mysql:5.7 container_name: mysql environment: MYSQL_ROOT_PASSWORD: root MYSQL_DATABASE: test_db MYSQL_USER: root MYSQL_PASSWORD: p@ssword TZ: 'Asia/Tokyo' command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci volumes: - ./docker/db/data:/var/lib/mysql - ./docker/db/my.cnf:/etc/mysql/conf.d/my.cnf - ./docker/db/sql:/docker-entrypoint-initdb.d ports: - 3306:3306
-
create_table.sql
create table IF not exists `test_table` ( `id` INT(20) AUTO_INCREMENT, `name` VARCHAR(20) NOT NULL, `created_at` Datetime DEFAULT NULL, `updated_at` Datetime DEFAULT NULL, PRIMARY KEY (`id`) ) DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
-
次のようなデータを登録しておく。
id, name, created_at, updated_at
1, test, 2019-10-04 15:25:07, 2019-10-04 15:25:07
2, test2, 2019-10-04 15:25:07, 2019-10-04 15:25:07
3, test3, 2019-10-04 15:25:07, 2019-10-04 15:25:07
バックアップ(ダンプ)コマンド
docker exec -it mysql mysqldump -u root -pp@ssword test_db > dump.sql
テーブル指定
docker exec -it mysql mysqldump -u root -pp@ssword test_db test_table > dump.sql
条件指定
# = 句
docker exec -it mysql mysqldump -u root -pp@ssword test_db test_table --where 'id = 1' > dump3.sql
# IN 句
docker exec -it mysql mysqldump -u root -pp@ssword test_db test_table --where 'id in (1,2)' > dump4.sql
リストアコマンド
docker exec -it mysql mysql -u root -pp@ssword test_db -e"$(cat dump.sql)"