Fix: Access denied for user ‘root’@’localhost’ in MariaDB

If you’re getting an error telling you that access is denied for the root user in MariaDB, this article may help.

The Error

I was attempting to import my system’s time zone information into MariaDB with the following command:

mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql

But it resulted in the following error:

ERROR 1698 (28000): Access denied for user 'root'@'localhost'

The Cause

After investigating this, I realised that the root user had yet not had its password set.

When I ran the following query:

SELECT user, password 
FROM user
WHERE User = 'root';

I got the following result:

+-------------+----------+
| User        | Password |
+-------------+----------+
| root        | invalid  |
+-------------+----------+

The MariaDB documentation states the following:

Still, some users may wish to log in as MariaDB root without using sudo. Hence the old authentication method — conventional MariaDB password — is still available. By default it is disabled (“invalid” is not a valid password hash), but one can set the password with a usual SET PASSWORD statement. And still retain the password-less access via sudo.

So that looks like our answer.

The Solution

As per the above paragraph, I needed to set the password for the root user:

SET PASSWORD FOR 'root'@localhost = PASSWORD("myReallyStrongPwd");

Running that (with a different password) did the trick.

So if getting the above error, perhaps this will help.