2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

初学者向け:AlmaLinuxにMySQLをインストールし、基本的なCRUD操作をしてみた

Last updated at Posted at 2024-10-14

はじめに

今回は、自宅のVirtualBox上で稼働しているAlmaLinuxにMySQLを導入し、簡単なCRUD(Create, Read, Update, Delete)の操作を実行する方法を紹介します。

AlmaLinuxはCentOSの後継として人気があり、MySQLは多くのアプリケーションで使用されるデータベース管理システムです。

本記事では、基本的なインストール手順から実際にデータベースを作成し、CRUD操作を行う方法まで解説します。

前提条件

本記事では以下の環境を前提としています。

・OS: AlmaLinux(CentOSの後継)
・仮想環境: VirtualBox
・ネットワーク: インターネットに接続可能であること

事前にAlmaLinuxがVirtualBox上で稼働していることを確認してください。

image.png

知識整理

AlmaLinuxはRed Hat系のLinuxディストリビューションで、CentOSの代替として多くのサーバー環境で利用されています。

MySQLは関係データベース管理システム(RDBMS)で、構造化されたデータを効率的に管理できます。

AlmaLinuxにMySQLを導入するには、MySQLのリポジトリを追加し、パッケージマネージャ(dnf)を使用してインストールを行います。

インストール後は、データベースを作成し、簡単なCRUD操作をハンズオンしてみます!

データベースの作成の流れ

まず、MySQLをAlmaLinuxにインストールする手順を解説します。

MySQLの導入

MySQL公式のリポジトリを追加するため、以下のコマンドでMySQLのリポジトリをダウンロードしてインストールします。

sudo dnf install https://dev.mysql.com/get/mysql80-community-release-el8-1.noarch.rpm

実際のインストール画面

image.png

・・・・(省略)
Running transaction
  Preparing        :                                                                                                             1/1
  Installing       : mysql80-community-release-el8-1.noarch                                                                      1/1
  Verifying        : mysql80-community-release-el8-1.noarch                                                                      1/1

Installed:
  mysql80-community-release-el8-1.noarch

Complete!
You have new mail in /var/spool/mail/root

MySQLのリポジトリが正しく追加されているか確認します。

sudo dnf repolist enabled | grep mysql

正常に追加されていれば、「mysql80-community」が表示されるはずです。

[root@HONDA-TEST ~]# sudo dnf repolist enabled | grep mysql
mysql-connectors-community MySQL Connectors Community
mysql-tools-community      MySQL Tools Community
mysql80-community          MySQL 8.0 Community Server
You have new mail in /var/spool/mail/root

MySQLの最新バージョンをインストールします。

sudo dnf install mysql-server

MySQLサービスを起動し、OS起動時に自動で起動するように設定します。

sudo systemctl start mysqld
sudo systemctl enable mysqld

MySQLのインストール後、初期設定が必要です。mysql_secure_installationを実行し、初期のセキュリティ設定を行います。

sudo mysql_secure_installation

必要に応じて、新しいパスワードの設定や匿名ユーザーの削除、テストデータベースの削除などが求められますので、指示に従って入力してください。

[root@HONDA-TEST mysql]# sudo mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root:
The 'validate_password' component is installed on the server.
The subsequent steps will run with the existing configuration
of the component.
Using existing password for root.

Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) : y

New password:

Re-enter new password:

Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : y
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : y
Success.

All done!
You have new mail in /var/spool/mail/root

ここでは、rootユーザーのパスワード設定や不要なユーザーの削除を行います。rootユーザーとしてMySQLにログインします。

sudo mysql -u root -p

パスワードを入力すると、MySQLにログインできます。

データベースの作成

次に、新しいデータベースを作成します。test_dbというデータベースが作成されます。

CREATE DATABASE test_db;

新しいユーザーを作成し、データベースにアクセスできるように権限を付与します。これで、test_userがtest_dbにアクセスできるようになります。

CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'StrongPassword123!';
GRANT ALL PRIVILEGES ON test_db.* TO 'test_user'@'localhost';
FLUSH PRIVILEGES;

Query OK, 0 rows affected (0.10 sec)」となり、成功していることが確認できました。

以下のコマンドで「test_user」としてログインできます。

sudo mysql -u test_user -p

簡単なCRUDの処理の検証

CRUDとは、データベースの基本的な操作であるCreate(作成)、Read(読み取り)、Update(更新)、Delete(削除)の略です。

以下では、具体的にCRUD操作を行う例をもとに詳細な説明を加えます。

テーブルの作成

まず、CRUD操作を行うためのテーブルを作成します。

USE test_db;
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100),
    age INT
);

ここでの簡単な説明は以下になります。

・id: 自動増分の整数型(主キー)。
・name: 最大100文字の文字列型。
・age: 整数型。

Create(データの作成)

新しいユーザーを追加します。これでusersテーブルにAliceとBobのレコードが作成されます。

mysql> INSERT INTO users (name, age) VALUES ('Alice', 30), ('Bob', 25);
Query OK, 2 rows affected (0.04 sec)
Records: 2  Duplicates: 0  Warnings: 0

Read(データの読み取り)

テーブルからデータを取得します。usersテーブル内の全データを表示します。

mysql> SELECT * FROM users;
+----+-------+------+
| id | name  | age  |
+----+-------+------+
|  1 | Alice |   30 |
|  2 | Bob   |   25 |
+----+-------+------+
2 rows in set (0.00 sec)

Update(データの更新)

特定のユーザーの情報を変更します。nameがBobのレコードのageを26に更新します。

mysql> UPDATE users SET age = 26 WHERE name = 'Bob';
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

Delete(データの削除)

特定のユーザーを削除します。nameがAliceのレコードを削除します。

mysql> DELETE FROM users WHERE name = 'Alice';
Query OK, 1 row affected (0.02 sec)

Aliceさんのレコードが削除されていることが確認できました。

mysql> SELECT * FROM users;
+----+------+------+
| id | name | age  |
+----+------+------+
|  2 | Bob  |   26 |
+----+------+------+
1 row in set (0.00 sec)

まとめ

この記事では、VirtualBox上のAlmaLinuxにMySQLを導入する手順と、簡単なCRUD操作の検証方法を解説しました。

MySQLのインストールは比較的簡単ですが、初期設定やセキュリティに注意することが重要です。

また、基本的なCRUD操作を通じて、MySQLの操作感をつかむことができたかと思います。

ぜひ、自分の環境でも試してみてください!

参考文献

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?