在 Linux 上安裝 MySQL 或 MariaDB

前言廢話

其實啦,這本該是一篇很基本的文章。但我似乎一直都沒有寫一篇來專門介紹如何在 Linux 上安裝 SQL 的教學,因此就想說應該可以水一篇文章

下文的安裝環境會在 Ubuntu 上安裝 MariaDB,但其實 MySQL 也可以參照這篇文章操作,下方會提到。

安裝資料庫

那就先將我們的系統更新吧!

sudo apt-get -y update && sudo apt-get -y upgrade

接著這步就是安裝 MySQL 或是 MariaDB 啦!

如果你是要安裝 MySQL 的話:

sudo apt-get install -y mysql-server

如果你是要安裝 MariaDB 的話:

sudo apt-get install -y mariadb-server

安裝完其實就好了,但是我們來進行安全設定。

進行安全設定

我們來執行一行命令進行安全設定。

sudo mysql_secure_installation

由於目前 root 並沒有設定任何密碼,這步我們直接按 Enter 即可。

NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 

這裡詢問我們是否需要為 root 設定密碼,我這裡選擇 Y。

OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] Y

是否刪除匿名用戶,輸入 Y。

By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB 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? [Y/n] Y

是否關閉 root 遠程登入,輸入 Y。

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? [Y/n] Y

是否移除測試資料庫,選擇 Y。

By default, MariaDB 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? [Y/n] Y

現在重新載入權限讓剛剛的設置保存嗎,選擇 Y。

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

Reload privilege tables now? [Y/n] Y

到這裡就完成安全設定囉!

建立資料庫

我們需要建立一個資料庫,才能存放資料。

進入資料庫

sudo mysql

進入之後,我們建立一個名為 test 的資料庫好了。

CREATE DATABASE test;

這樣就完成啦!

新增使用者並授予權限

當我們在撰寫程式碼並串接資料庫時,我們並不會直接使用 root 帳號。通常是建立一個帳號,並設定給他允許訪問的資料庫。

而這裡,我示範新增帳號,並授予他全部權限,你可以依照你的需求更改。

進入資料庫。

sudo mysql

建立一個名為 user 的使用者,且他的密碼為 123456

CREATE USER user@localhost IDENTIFIED BY '123456';

將任何資料庫的權限授予 user. 代表任何資料庫的任何資料表,可依照自己需求更改)。

GRANT ALL PRIVILEGES ON *.* TO user@localhost;

保存設定並離開。

flush privileges;
exit;

結語

其實這篇文章非常基礎,但我相信還是有些人沒辦法做出這些步驟,那就可以參考這篇文章。

而我呢,只是設定的時候不想自己打,所以記錄成一篇文章,之後就可以複製貼上囉