MariaDB ERROR 1698 (28000): Access denied for user 'root'@'localhost'対処法

MariaDBのインストール直後にログインできない。。。rootのパスワードも設定すらしてなくて空なはずなのに。ちょっとハマった。

MariaDBではデフォルト認証がUnix_Socketを使う設定なので、root権限でないとログインできない。sudoを使うと何の問題もなくログインできる。なので、認証プラグインをUnix_Socketからmysql_native_passwordに変更すればよい。

$ mysql -u root
ERROR 1698 (28000): Access denied for user 'root'@'localhost'
koichiro@u2004wp:~$ 
koichiro@u2004wp:~$ sudo mysql -u root
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 52
Server version: 10.3.22-MariaDB-1ubuntu1 Ubuntu 20.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]> USE mysql;
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
MariaDB [mysql]> 
MariaDB [mysql]> SELECT User, Host, plugin FROM mysql.user;
+------+-----------+-------------+
| User | Host      | plugin      |
+------+-----------+-------------+
| root | localhost | unix_socket |
+------+-----------+-------------+
1 row in set (0.001 sec)

MariaDB [mysql]> 
MariaDB [mysql]> UPDATE user SET plugin='mysql_native_password' WHERE User='root';
Query OK, 1 row affected (0.001 sec)
Rows matched: 1  Changed: 1  Warnings: 0

MariaDB [mysql]> SELECT User, Host, plugin FROM mysql.user;
+------+-----------+-----------------------+
| User | Host      | plugin                |
+------+-----------+-----------------------+
| root | localhost | mysql_native_password |
+------+-----------+-----------------------+
1 row in set (0.000 sec)

MariaDB [mysql]> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.001 sec)

MariaDB [mysql]> exit;
Bye
$ 
$ sudo systemctl restart mysql
$ 
$ mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 36
Server version: 10.3.22-MariaDB-1ubuntu1 Ubuntu 20.04

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>