Fix ERROR 1045: “Access denied for user…” in MySQL

If you’re getting error 1045 that reads something like “Access denied for user ‘root’@’localhost’“, it’s because you’re trying to log in to MySQL without the right credentials.

This usually happens when we provide the wrong password. But there could also be another cause. For example, we could be trying to do something as the root user that requires a password, but the root user hasn’t yet had its password set.

To fix this issue, be sure to provide the correct password when connecting to MySQL.

Example of Error

Here’s an example of code that produces the error:

mysql -uhomer -pWrongPwd

Result:

ERROR 1045 (28000): Access denied for user 'homer'@'localhost' (using password: YES)

In that example, I provided the wrong password.

Here’s another example that can cause the same error:

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

Result:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

Here I was trying to import named time zones into MySQL using the root user, and I provided a password, but the root user hadn’t yet had its password set.

Solution 1

The most obvious solution is to ensure that we pass the correct credentials when connecting to MySQL. In the first case above, I simply provided the wrong password.

Here’s an example of providing the correct password:

mysql -uhomer -pWheelyStrongPwd

Result:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 80
Server version: 8.0.29 Homebrew

Copyright (c) 2000, 2022, 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.

This time I was able to log in successfully using the homer account.

Solution 2

If you’re getting the error when trying to do something using the root user, it could be that the root user hasn’t yet had its password set.

In this case, set the password for the root user:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'WheelyStrongPwd';

Change WheelyStrongPwd to a really string password of your choosing.

Now when you try to log in as the root user, use the password that you set here.