[ MySQL ] 入門編: データベースの一覧表示、作成 、削除コマンド

Pocket

ここでは、MySQL でデータベースの一覧表示と作成と削除を行うサンプルを掲載しています。

スポンサーリンク

データベースの一覧を表示する ( show databases )

データベースの一覧を表示するには、show databases コマンドを使用します。

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.18 sec)

データベースを作成する ( create database )

データベースを作成するには、create database コマンドを使用します。

mysql> create database test_db;
Query OK, 1 row affected (0.04 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test_db            |
| test               |
+--------------------+
5 rows in set (0.00 sec)

既に存在するデータベースを再作成しようとするとエラーとなります。

エラー内容
ERROR 1007 (HY000): Can’t create database ‘test_db’; database exists

mysql> create database test_db;
ERROR 1007 (HY000): Can't create database 'test_db'; database exists

データベースがすでに存在する場合には、データベースの作成を行わないようにすることもできます。以下のように IF NOT EXISTS 構文を使用します。または、既に存在する場合はデータベースを削除して再度作成するという方法も考えられます。

mysql> create database if not exists test_db;
Query OK, 1 row affected, 1 warning (0.00 sec)

データベースを削除する ( drop database )

データベースを削除するには drop database コマンドを使用する。

mysql> drop database test_db;
Query OK, 0 rows affected (0.29 sec)

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)
参考
スポンサーリンク


Pocket

Leave a Comment

Your email address will not be published. Required fields are marked *