こんにちは、さるまりんです。
今回はMySQLデータベースの環境構築で最初にやるであろう、データベースの作成、ユーザーの作成、権限の付与についてメモしておきます。
MySQLをインストールし、立ち上げてrootユーザーで接続できることを前提とします。
まずはrootユーザーで繋ぎます。
続いて以下のコマンドでデータベースを作成します。
CREATE DATABASE saludb;
データベースsaludbを作成しました。
次はユーザーを作成します。
CREATE USER 'salu'@'localhost' IDENTIFIED BY 'salupw';
saluがユーザー名、@の後ろのlocalhostは接続元ホストです。
IDNTIFIED BYの後ろのsalupwはパスワードです。
接続元ホストにはIPアドレスを指定したり、'%'を指定してワイルドカードにすることもできます。
ワイルドカードバージョンです。
CREATE USER 'salu'@'%' IDENTIFIED BY 'salupw';
作成したユーザーにデータベースに対する権限を付与します。
GRANT ALL PRIVILEGES ON saludb.* TO 'salu'@'%';
ALL PRIVILEGESで全ての権限を付与しています。
全ての権限ではなくて制限して権限を付与することもできます。
例えば読み取りだけを許可したい場合はSELECTを指定します。
GRANT SELECT ON saludb.* TO 'monkey'@'localhost';
こうするとmokeyユーザーはデータベースに対して読み取り=SELECTを実行できる権限が与えられます。
rootユーザーで繋いで上のコマンドを実行してみました。
% mysql -u root -p -h 127.0.0.1
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 24
Server version: 8.0.25 MySQL Community Server - GPL
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
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 saludb;
Query OK, 1 row affected (0.01 sec)
mysql> CREATE USER 'salu'@'%' IDENTIFIED BY 'salupw';
Query OK, 0 rows affected (0.02 sec)
mysql> GRANT ALL PRIVILEGES ON saludb.* TO 'salu'@'%';
Query OK, 0 rows affected (0.02 sec)
mysql>
これでsaluユーザーで繋いでデータベースsaludbを操作することができます。
試しに接続して簡単なCREATE TABLE文を実行してみます。
% mysql -u salu -p -h 127.0.0.1 saludb
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 26
Server version: 8.0.25 MySQL Community Server - GPL
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
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 TABLE salu_sample (id INTEGER NOT NULL);
Query OK, 0 rows affected (0.05 sec)
mysql>
問題なく実行できました。
ユーザーの作成や権限付与って頻繁にやらないので忘れてしまいます。
ここにメモしておいたらまた戻ってこれるかな。日々勉強ですね。
読んでくださってありがとうございました。
それではまた!