MySQL(https://www.mysql.com/jp/)の操作に慣れたいと思い、よく使うであろうコマンドを備忘録として記録していきます。
今回はデータベース操作に関してまとめました。随時更新予定です。(シリーズ化したい)
ますはMySQLサーバへ接続しましょう。
localhostのログインコマンドはmysql -u root -pです。
% mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
...<中略>
mysql>データベースの作成(create database "DB名")
mysql> create database sample;
Query OK, 1 row affected (0.00 sec)上記コマンドは既に存在しているデータベース名で作成しようとするとエラーになるため、「create database if not exists "DB名"」とするのが一般的です。
mysql> create database if not exists sample;
Query OK, 1 row affected, 1 warning (0.00 sec)データベース一覧の確認(show databases)
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| sample |
+--------------------+
2 rows in set (0.00 sec)ワイルドカードによる絞り込みも可能です。
mysql> show databases like 'sa%';
+----------------+
| Database (sa%) |
+----------------+
| sample |
+----------------+
1 row in set (0.00 sec)また、データベース一覧の確認はMySQLにログイン状態でなくても可能です。
ログアウト状態でのコマンドはmysqlshowとなります。
% mysqlshow
+--------------------+
| Databases |
+--------------------+
| information_schema |
| sample |
+--------------------+データベースの作成文の確認(show create database "DB名"\G)
mysql> show create database sample\G
*************************** 1. row ***************************
Database: sample
Create Database: CREATE DATABASE `sample` /*!40100 DEFAULT CHARACTER SET utf8 */
1 row in set (0.00 sec)データベースの選択(use "DB名")
mysql> use sample;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changedデータベースの削除(drop database "DB名")
mysql> drop database sample;
Query OK, 1 row affected (0.00 sec)