535

Consider:

./mysqladmin -u root -p** '_redacted_'  

Output (including typing the password):

Enter password:

mysqladmin: connect to server at 'localhost' failed error:
'Access denied for user 'root'@'localhost' (using password: YES)'

How can I fix this?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Harsh Trivedi
  • 5,591
  • 3
  • 12
  • 14
  • 5
    Possible duplicate of [Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)](http://stackoverflow.com/questions/6081339/access-denied-for-user-rootlocalhost-using-password-yes-mysqlerror) – clearlight Jan 14 '17 at 00:13
  • 1
    @clearlight Is not same question, this post is a problem with mysqladmin win super privilegies into mysql, the other post is a problem with a simple connection from socket. – e-info128 Mar 22 '18 at 02:27
  • Try remove if exists `~/.my.cnf` file. – e-info128 Mar 22 '18 at 03:23
  • 44
    I know this is old, but want to say this for future visitors. Don't enter your mysql password, especially for root, in the command itself, or it will be stored in your shell history. Just leave the `-p` option by itself and mysql will prompt for a password. – Scotty C. May 09 '18 at 21:58
  • 1
    For MySQL 8 use sudo mysql_secure_installation and set an strong password. Ref. Check step 5 of this tutorial https://phoenixnap.com/kb/how-to-install-mysql-on-ubuntu-18-04 – Jhon Didier Sotto Nov 17 '20 at 21:14

28 Answers28

1029

All solutions I found were much more complex than necessary and none worked for me. Here is the solution that solved my problem. There isn't any need to restart mysqld or start it with special privileges.

sudo mysql

-- for MySQL
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';

-- for MariaDB
ALTER USER 'root'@'localhost' IDENTIFIED VIA mysql_native_password USING PASSWORD('root');

With a single query we are changing the auth_plugin to mysql_native_password and setting the root password to root (feel free to change it in the query).

Now you should be able to log in with root. More information can be found in MySQL documentation or MariaDB documentation.

(Exit the MySQL console with Ctrl + D or by typing exit.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
svet
  • 11,078
  • 1
  • 15
  • 26
  • 70
    I'm unable to do this... "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near...". – TCB13 Nov 12 '17 at 16:47
  • 5
    This answer worked, I accidentally added is not useful answer vote, excuse me! – taher Feb 07 '18 at 16:35
  • 4
    Single line version: **sudo mysql -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root'"** – svet Jun 19 '18 at 09:58
  • 36
    Worked very well on Ubuntu 18.04 – Almino Melo Jul 30 '18 at 19:46
  • 3
    @TCB13 and anyone else facing this issue. "I 'm unable to do this... "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near... ". Use FLUSH PRIVILEGES before executing the alter command – coder Feb 19 '19 at 13:18
  • 1
    Works on Ubuntu 19.04 – Nicolas Raoul Apr 12 '19 at 02:27
  • This worked a treat for me as well, thank you! I was able to log in fine from the command line but not over TOAD using an SSH tunnel using the same credentials. It was driving me nuts so I'm rapt that it's working now. – ChrisFNZ May 02 '19 at 01:33
  • 11
    This locked me out, even sudo mysql no longer works. Had to completely remove mysql and reinstall. – jjxtra Jun 12 '19 at 19:37
  • 1
    ERROR 1819 (HY000): Your password does not satisfy the current policy requirements seems you have to set a very secure password with version 5.7.27 – Josh Nov 10 '19 at 10:58
  • @Josh You need to change your mysql policy. `sudo mysql` and then `SET GLOBAL validate_password_length = 4;` – MCFreddie777 Apr 03 '20 at 10:16
  • Those guys who have problems with ERROR in SQL syntax, check your `mysql --version`. If you have 8+, the `INDENTIFIED BY` keyword has changed. Therefore this fix is for mysql5.7. – MCFreddie777 Apr 03 '20 at 10:18
  • 1
    Finally, an answer that worked for me on Ubuntu 20.04. – Ruben Alves Jun 22 '20 at 14:50
  • 1
    even if it says 0 rows affected it will update the password to be 'root' – Ahmed Aboud Jul 02 '20 at 10:28
  • Still works in `MySQL 5.7.31`, 2020. I changed the password to empty and my configurations are correct, but I couldn't login with root, this saves my time. Thank you. – Yushan ZHANG Aug 11 '20 at 03:33
  • 1
    This worked! Wanted to note something a bit misleading that happened to me. When I entered it, it returned `Query OK, 0 rows affected (0.01 sec)`. As if it didn't do anything, but it still worked. Because when I try to connect to it, now it works and I did nothing else between. Thanks again for this. Lifesaver. – Stephen Sabatini Jan 22 '21 at 22:52
  • Yay! Ubuntu 20.04 solution. (I'm getting real tired of MySQL screwing with things like this). @harsh-trivedi this should be the accepted answer. – Trees4theForest Feb 02 '21 at 22:55
  • 1
    For those getting an MariaDB error listed on the top comment, please scroll down to this answer: https://stackoverflow.com/a/57311757/1463744 which worked for me! – fagiani Mar 02 '21 at 14:41
  • 3
    `sudo mysql` gives `ERROR 1045 (28000): Access denied for user 'root'@'localhost'` (both with and without the password) – Rodrigo Jul 21 '21 at 15:52
  • Worked on Ubuntu 21.04. Thanks! – Pedram Soheil Aug 01 '21 at 02:22
  • Worked, but I wish I knew why my MySQL root password keeps getting reset. I know I'll have to deal with this problem again and again. – Throw Away Account Dec 14 '21 at 07:19
  • Just wanted to say that I spent 2 hours looking for an answer to this problem. You saved my day. Worked on Ubuntu 21.10. Thanks! – Francisco Junior Feb 03 '22 at 11:48
  • I am on mysql 8.0.28, ubuntu 20.04.3. This solution worked. I can now do "mysql -u root -p" and get in. HOWEVER, sudo mysql does not work anymore. I get an error - Access denied for user 'root'@'localhost'. – Dr Phil Feb 11 '22 at 17:40
  • The USING clause at the end of the Mariadb command is only valid in Mariadb v10.4 onwards: https://mariadb.com/kb/en/alter-user/#authentication-options – racitup Apr 22 '22 at 19:30
645
  1. Open and edit /etc/my.cnf or /etc/mysql/my.cnf, depending on your distribution.
  2. Add skip-grant-tables under [mysqld]
  3. Restart MySQL
  4. You should be able to log in to MySQL now using the below command mysql -u root -p
  5. Run mysql> flush privileges;
  6. Set new password by ALTER USER 'root'@'localhost' IDENTIFIED BY 'NewPassword';
  7. Go back to /etc/my.cnf and remove/comment skip-grant-tables
  8. Restart MySQL
  9. Now you will be able to login with the new password mysql -u root -p
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kishore Venkataramanan
  • 6,799
  • 1
  • 12
  • 11
  • 6
    Hello, I had the same problem. I did the above, and it solve the problem, but everytime I reboot CentOS, I need to do all of the steps again (I got the message:Access denied for user 'root'@'localhost' (using password: NO) - when run the command mysql (or any sql command) and I do again and again all over as above at each reboot. – Eitan Apr 01 '17 at 21:47
  • 1
    I have the exact same problem as Eitan does. – BILL WAGNER Apr 11 '17 at 23:03
  • 1
    This is the ONLY solution that worked for me. All other of trying to skip grant tables running mysql --skip.., etc. failed – schmoopy Oct 11 '17 at 19:06
  • More details about this solution here, https://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html – Pedro Angel Nov 07 '17 at 05:56
  • 26
    Too bad that this does not work with MariaDB: ``You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'USER 'root'@'localhost' IDENTIFIED BY 'NewPassword'' at line 1`` – Philipp Ludwig Mar 13 '18 at 21:20
  • In my case I've added `skip_grant_tables` (mysql5.7) – David Goloviy Apr 18 '18 at 15:12
  • 1
    it works. @PhilippLudwig you might need to use different way. In my case will be use mysql; then UPDATE user SET Password=PASSWORD('YOUR_NEW_PASS') where USER='root'; – Edwin Wong Apr 21 '18 at 21:54
  • 14
    I found this to work @PhilippLudwig `set PASSWORD FOR 'root'@'localhost' = PASSWORD('root');` I did this after step 5. Here is how my command prompt output looked: `MariaDB [(none)]> MariaDB [(none)]> set PASSWORD FOR 'root'@'localhost' = PASSWORD('root'); Query OK, 0 rows affected (0.00 sec)` – therobyouknow Apr 27 '18 at 12:55
  • 6
    For step 3 restart MariaDB: I found the following works: `sudo systemctl restart mariadb` – therobyouknow Apr 27 '18 at 13:01
  • 7
    Some may find the file in /etc/mysql/my.cnf – DSinghvi Aug 18 '18 at 16:21
  • 4
    ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded – ospider Sep 21 '18 at 07:08
  • 1
    As an alternative, you can execute `sudo mysqld_safe --skip-grant-tables` and open a second terminal to enter `mysql -u root -p` without the need to modify and configuration files. – Abandoned Cart Oct 19 '18 at 07:59
  • @Eitan permissions matter, chances are you have installed mysql when logged as root user. try `sudo su` and `mysql -u root -p` and you'll logged in without issue, but with big security concerns.. – fiorentinoing Nov 05 '18 at 16:15
  • I use mac and I run this command "$ sudo find / -name my.cnf" to find location of my.cnf , and it worked after follow above steps. – KHACHORNCHIT Jun 15 '19 at 14:18
  • If you get: "You are using MariaDB as an anonymous user and anonymous users are not allowed to modify user settings" you can find solution https://stackoverflow.com/questions/49926467/you-are-using-mariadb-as-an-anonymous-user – Vladimir Sep 05 '19 at 11:24
  • Found my file in this directory -> /etc/mysql/mysql.conf.d – yanike Sep 30 '19 at 05:37
  • 2
    this trick appears to no longer be valid. Server version 5.7.27 forbids altering the root password while --skip-grant-tables is in effect – mreff555 Oct 09 '19 at 23:39
  • 1
    In Ubuntu 18.04 and MySQL 5.7.28, the config file is placed at /etc/mysql/mysql.conf.d/mysqld.cnf – MRazian Dec 29 '19 at 13:39
  • 1
    When I want to alter the password I get the following error (MySQL8) `ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement` I've followed this suggestions to fix it: https://askubuntu.com/questions/766334/cant-login-as-mysql-user-root-from-normal-user-account-in-ubuntu-16-04 – Tajs Apr 04 '20 at 10:14
  • that solved it in fedora30, the config file was under /etc/my.cnf.d/community-mysql-server.cnf Many thanks @Kishore Venkataramanan – bliako May 03 '20 at 18:04
  • best solution. i am using ubuntu 20.04 configuration file path is /etc/mysql/mysql.conf.d. Thanks. – Tolga Sahin Jun 15 '20 at 18:08
  • 1
    Great answer, I just add that I had to add 'ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';' at point 6 (it was auth_socket by default) – KHanusova Aug 19 '20 at 17:44
  • I was able to run `mysqladmin --user=root password "password"` after the second step – KTM Oct 14 '20 at 04:47
  • 2
    The top answers are ALL BAD. To save hours of time use this answer - https://stackoverflow.com/a/58155034/4759176 This answer in particular costed me an hour. DON'T USE THIS ANSWER. EDITING THE CONFIG FILE results in `Couldn't connect` error which leads you down a new rabbithole. For your sake use the answer I linked above ^ – parsecer Dec 01 '20 at 01:32
  • Is it really so complicated and why. I had to do the steps from this answer, and the steps from two other answers just to have the localhost user working. – makkasi Mar 08 '21 at 17:34
  • I changed it with `sudo vim /etc/mysql/mariadb.conf.d/50-server.cnf` on a raspian install of mariadb. Great answer. Thanks. – emccracken Jul 19 '21 at 19:46
  • I think it would be also good to temporarily turn off remote port or add firewall rule so no one could connect from the network in the meantime. – Zbyszek Jul 29 '21 at 20:18
  • after given command running `sudo mysql` it throws error ``ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO) ``` – Rajanboy Jun 24 '22 at 14:58
  • Whoever reads this - I discovered that for mysql running from docker container my password was too long for client to be able to successfully authenticate with it. I shrank the password to 79 characters and this solved my problem. This problem seems to be linked with mysql client itself, because joomla app which was using another user with long password was happily authenticating to that very same server. – Greg0ry Feb 10 '23 at 21:42
  • Worked for RedHat 7 – Bastion Apr 11 '23 at 01:01
136

None of the previous answers helped me with this problem, so here's the solution I found.

The relevant part:

In Ubuntu systems running MySQL 5.7 (and later versions), the root MySQL user is set to authenticate using the auth_socket plugin by default rather than with a password. This allows for some greater security and usability in many cases, but it can also complicate things when you need to allow an external program (e.g., phpMyAdmin) to access the user.

In order to use a password to connect to MySQL as root, you will need to switch its authentication method from auth_socket to mysql_native_password. To do this, open up the MySQL prompt from your terminal:

sudo mysql

Next, check which authentication method each of your MySQL user accounts use with the following command:

SELECT user,authentication_string,plugin,host FROM mysql.user;

Output

+------------------+-------------------------------------------+-----------------------+-----------+
| user             | authentication_string                     | plugin                | host      |
+------------------+-------------------------------------------+-----------------------+-----------+
| root             |                                           | auth_socket           | localhost |
| mysql.session    | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys        | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *CC744277A401A7D25BE1CA89AFF17BF607F876FF | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
4 rows in set (0.00 sec)

In this example, you can see that the root user does in fact authenticate using the auth_socket plugin. To configure the root account to authenticate with a password, run the following ALTER USER command. Be sure to change password to a strong password of your choosing, and note that this command will change the root password you set in Step 2:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

Then, run FLUSH PRIVILEGES which tells the server to reload the grant tables and put your new changes into effect:

FLUSH PRIVILEGES;

Check the authentication methods employed by each of your users again to confirm that root no longer authenticates using the auth_socket plugin:

SELECT user,authentication_string,plugin,host FROM mysql.user;

Output

+------------------+-------------------------------------------+-----------------------+-----------+
| user             | authentication_string                     | plugin                | host      |
+------------------+-------------------------------------------+-----------------------+-----------+
| root             | *3636DACC8616D997782ADD0839F92C1571D6D78F | mysql_native_password | localhost |
| mysql.session    | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| mysql.sys        | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE | mysql_native_password | localhost |
| debian-sys-maint | *CC744277A401A7D25BE1CA89AFF17BF607F876FF | mysql_native_password | localhost |
+------------------+-------------------------------------------+-----------------------+-----------+
4 rows in set (0.00 sec)

You can see in this example output that the root MySQL user now authenticates using a password. Once you confirm this on your own server, you can exit the MySQL shell:

exit

AvahW
  • 2,083
  • 3
  • 24
  • 30
  • 1
    Worx also for `mysql Ver 8.0.20-0ubuntu0.20.04.1 for Linux on x86_64 ((Ubuntu))` on `ubuntu 20.04`. Cheers – Jadeye Jul 23 '20 at 18:57
  • Anybody facing the issue for MySQL inside Docker.. this is the solution for you guys. Thanks! – Fahad Javed Jul 28 '20 at 08:52
  • 1
    In Debian 10, the plugin is not auth_socket but `unix_socket`. – Timo Oct 21 '20 at 09:27
  • Can you fix the formatting problems (also in the first revision)? – Peter Mortensen Sep 21 '21 at 18:19
  • 2
    I'm recieving this error, why? `You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'BY 'MYPERSONALPASSWORD'' at line 1` I've just pasted this line: `ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'MYPERSONALPASSWORD';` – Fernando Torres Oct 09 '21 at 23:44
  • @FernandoTorres I've just tested that line and it worked as expected. You could try cop/pasting the line again, manually typing it out, and/or switching to a new terminal instance – AvahW Oct 10 '21 at 16:28
  • by far the most simple and best answer here!!! – lacostenycoder Dec 30 '22 at 16:59
88

I tried many steps to get this issue corrected. There are so many sources for possible solutions to this issue that is is hard to filter out the sense from the nonsense. I finally found a good solution here:

Step 1: Identify the database version

mysql --version

You'll see some output like this with MySQL:

mysql  Ver 14.14 Distrib 5.7.16, for Linux (x86_64) using  EditLine wrapper

Or output like this for MariaDB:

mysql  Ver 15.1 Distrib 5.5.52-MariaDB, for Linux (x86_64) using readline 5.1

Make note of which database and which version you're running, as you'll use them later. Next, you need to stop the database so you can access it manually.

Step 2: Stopping the database server

To change the root password, you have to shut down the database server beforehand.

You can do that for MySQL with:

sudo systemctl stop mysql

And for MariaDB with:

sudo systemctl stop mariadb

Step 3: Restarting the database server without permission checking

If you run MySQL and MariaDB without loading information about user privileges, it will allow you to access the database command line with root privileges without providing a password. This will allow you to gain access to the database without knowing it.

To do this, you need to stop the database from loading the grant tables, which store user privilege information. Because this is a bit of a security risk, you should also skip networking as well to prevent other clients from connecting.

Start the database without loading the grant tables or enabling networking:

sudo mysqld_safe --skip-grant-tables --skip-networking &

The ampersand at the end of this command will make this process run in the background so you can continue to use your terminal.

Now you can connect to the database as the root user, which should not ask for a password.

mysql -u root

You'll immediately see a database shell prompt instead.

MySQL Prompt

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

mysql>

MariaDB Prompt

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

MariaDB [(none)]>

Now that you have root access, you can change the root password.

Step 4: Changing the root password

mysql> FLUSH PRIVILEGES;

Now we can actually change the root password.

For MySQL 5.7.6 and newer as well as MariaDB 10.1.20 and newer, use the following command:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';

For MySQL 5.7.5 and older as well as MariaDB 10.1.20 and older, use:

mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');

Make sure to replace new_password with your new password of choice.

Note: If the ALTER USER command doesn't work, it's usually indicative of a bigger problem. However, you can try UPDATE ... SET to reset the root password instead.

[IMPORTANT] This is the specific line that fixed my particular issue:

mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';

Remember to reload the grant tables after this.

In either case, you should see confirmation that the command has been successfully executed.

Query OK, 0 rows affected (0.00 sec)

The password has been changed, so you can now stop the manual instance of the database server and restart it as it was before.

Step 5: Restart the Database Server Normally

The tutorial goes into some further steps to restart the database, but the only piece I used was this:

For MySQL, use:

sudo systemctl start mysql

For MariaDB, use:

sudo systemctl start mariadb

Now you can confirm that the new password has been applied correctly by running:

mysql -u root -p

The command should now prompt for the newly assigned password. Enter it, and you should gain access to the database prompt as expected.

Conclusion

You now have administrative access to the MySQL or MariaDB server restored. Make sure the new root password you choose is strong and secure and keep it in safe place.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Blairg23
  • 11,334
  • 6
  • 72
  • 72
  • 1
    The ALTER USER statement was introduced in MariaDB 10.2.0. – Benoit Desrosiers Nov 29 '18 at 04:42
  • 3
    Wow ! this very line `mysql> UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';` has been such a life saver for me ! – lucyjosef Mar 22 '19 at 10:17
  • I use MariaDB 10.3.25 and this worked: `mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');` – Timo Oct 21 '20 at 09:38
  • I like this method, as it allowed me to temporarily create a database backup without permanently amending permissions, although it may have been better to not run `mysqld_safe` in the background as I seemed to get issues afterwards trying to kill it and then get the mysql service running normally again (although a full Linux restart seemed to do the trick). – SharpC Mar 09 '21 at 11:34
  • `-bash: mysqld_safe: command not found` `AlmaLinux release 8.5 ` – Salem May 17 '22 at 03:11
60

After trying all others answers, this it what finally worked for me:

sudo mysql -- It does not ask me for any password

-- Then in MariaDB/MySQL console:
update mysql.user set plugin = 'mysql_native_password' where User='root';
FLUSH PRIVILEGES;
exit;

I found the answer in the blog post Solved: Error “Access denied for user ‘root’@’localhost’” of MySQL — codementor.tech (Medium).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pico12
  • 1,229
  • 12
  • 18
  • 3
    THIS PLUGIN LINE IS REALLY HELPFUL. I tried a lot of compinations but this is the only worked for Ver 14.14 Distrib 5.7.27, for Linux (x86_64) – Alexey Nikonov Aug 13 '19 at 08:30
  • 4
    This helped me with mysql 5.7 as well. So applicable not only for mariadb – podarok Aug 23 '19 at 07:13
  • I just used this on MySQL 8 Ubuntu 20.04 and it worked. Other answers using `skip-grant-table` (my.conf or in `mysql` command) didn't work. I could get in using a service account (https://askubuntu.com/a/120769/169836) but `UPDATE mysql.user SET Password=PASSWORD('') WHERE User='root';` didn't work. Only when when using the plugin part did things work. Thanks~ – hamx0r Apr 30 '20 at 22:38
  • This helped me with my sql 8 and Ubuntu 20.04. – Supun Madhushanka Aug 02 '21 at 03:28
  • What is that plugin supposed to do? Can you link to official documentation? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/57311757/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 21 '21 at 16:09
  • This locked me out and I am no longer able to login with root. It just keeps throwing ```Access denied for user 'root'@'localhost' (using password: YES)```. As I am able to login with other users, I ran ```SELECT user,password_last_changed FROM mysql.user;``` and it shows that the password is not updated. Then why the hell I am not able to login? This is weird. – nkhl Jan 16 '23 at 12:30
40

For Ubuntu/Debian users

(It may work on other distributions, especially Debian-based ones.)

Run the following to connect as root (without any password)

sudo /usr/bin/mysql --defaults-file=/etc/mysql/debian.cnf

If you don't want to add --defaults-file each time you want to connect as root, you can copy /etc/mysql/debian.cnf into your home directory:

sudo cp /etc/mysql/debian.cnf ~/.my.cnf

And then:

sudo mysql
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fab
  • 14,327
  • 5
  • 49
  • 68
36

In my experience, if you run without sudo it will not work. So make sure your command is;

sudo mysql -uroot -p
Douglas Hosea
  • 1,002
  • 13
  • 30
  • 5
    This should be the acepted answer. The question is not about a forgotten password, but about the error message, because you cannot login as root without running with sudo privileges. – nivs1978 Nov 19 '20 at 09:52
  • 3
    The top answers are ALL BAD. To save hours of time use this answer - https://stackoverflow.com/a/58155034/4759176 – parsecer Dec 01 '20 at 01:32
  • 1
    This should be the top answer. Take my upvote. Thank you – Wahib Mkadmi Mar 13 '21 at 23:00
  • Extended in [Waterreedshimmer Dracchingan's answer](https://stackoverflow.com/questions/41645309/mysql-error-access-denied-for-user-rootlocalhost/68874182#68874182). – Peter Mortensen Sep 21 '21 at 18:20
20

For new Linux users this could be a daunting task. Let me update this with MySQL 8 (the latest version available right now is 8.0.12 as on 2018-09-12)

  1. Open "mysqld.cnf" configuration file at "/etc/mysql/mysql.conf.d/".
  2. Add skip-grant-tables to the next line of [mysql] text and save.
  3. Restart the MySQL service as "sudo service mysql restart". Now your MySQL is free of any authentication.
  4. Connect to the MySQL client (also known as mysql-shell) as mysql -u root -p. There is no password to be keyed in as of now.
  5. Run SQL command flush privileges;
  6. Reset the password now as ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPassword';
  7. Now let's get back to the normal state; remove that line "skip-grant-tables" from "mysqld.cnf" and restart the service.

That's it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Amit Kumar
  • 813
  • 11
  • 13
  • `mysql -u root -p` still ask for password `ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)` – Salem May 17 '22 at 03:14
  • @Salem try with sudo, that should work – Amit Kumar May 19 '22 at 15:46
  • when I ran these steps I get this error at step #6 : "ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement" – madacoda Dec 10 '22 at 22:49
14

In my case under Debian 10, the error

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

was solved by (good way)

sudo mysql -u root -p mysql

Bad way:

mysql -u root -p mysql
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
klor
  • 1,237
  • 4
  • 12
  • 37
  • 1
    This solved the issue. Just giving the permission with sudo (without password) so executed like: sudo mysql -u root -p – Ali Obeid Aug 16 '21 at 13:25
11

My Station here:

  • UBUNTU 21.04

  • PHP 5.6.40-57

  • MYSQL 5.7.37

let's config it

nano /etc/mysql/mysql.conf.d/mysqld.cnf

at the bottom, write this

skip-grant-tables

reload it

service mysql restart
PYK
  • 3,674
  • 29
  • 17
8

I did this to set my root password in the initial set up of MySQL in OS X. Open a terminal.

sudo sh -c 'echo /usr/local/mysql/bin > /etc/paths.d/mysql'

Close the terminal and open a new terminal.

And the following worked in Linux, to set the root password.

sudo /usr/local/mysql/support-files/mysql.server stop
sudo mysqld_safe --skip-grant-tables

(sudo mysqld_safe --skip-grant-tables: This did not work for me the first time. But on the second try, it was a success.)

Then log into MySQL:

mysql -u root

FLUSH PRIVILEGES;

Now change the password:

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

Restart MySQL:

sudo /usr/local/mysql/support-files/mysql.server stop
sudo /usr/local/mysql/support-files/mysql.server start
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sadee
  • 3,010
  • 35
  • 36
5

In your MySQL Workbench, you can go to the left sidebar, under Management select "Users and Privileges", click root under User Accounts, in the right section click tab "Account Limits" to increase the maximum queries, updates, etc., and then click tab "Administrative Roles" and check the boxes to give the account access.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Colleen Purcell
  • 473
  • 5
  • 7
5

Use sudo to alter your password:

sudo mysql

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'insert_password';

Source: Phoenixnap - Access denied for user root localhost

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
4

Ugh - nothing worked for me! I have a CentOS 7.4 machine running MariaDB 5.5.64.

I had to do this, right after installation of MariaDB from YUM;

systemctl restart mariadb
mysql_secure_installation

The mysql_secure_installation will take you through a number of steps, including "Set root password? [Y/n]". Just say "y" and give it a password. Answer the other questions as you wish.

Then you can get in with your password, using

mysql -u root -p

It will survive

systemctl restart mariadb

The Key

Then, I checked the /bin/mysql_secure_installation source code to find out how it was magically able to change the root password and none of the other answers here could. The import bit is:

do_query "UPDATE mysql.user SET Password=PASSWORD('$esc_pass') WHERE User='root';"

...It says SET Password=... and not SET authentication_string = PASSWORD.... So, the proper procedure for this version (5.5.64) is:

Log in using mysql -u root -p, using the password you already set.

Or, stop the database and start it with:

mysql_safe --skip-grant-tables --skip-networking &

From the mysql> prompt:

use mysql;
select host,user,password from user where user = 'root';
(observe your existing passwords for root).
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root' AND host = 'localhost';
select host,user,password from user where user = 'root';
flush privileges;
quit;

Kill the running mysqld_safe. Restart MariaDB. Log in as root: mysql -u -p. Use your new password.

If you want, you can set all the root passwords at once. I think this is wise:

mysql -u root -p

(login)
use mysql;
select host,user,password from user where user = 'root';
UPDATE mysql.user set Password = PASSWORD('your_new_cleartext_password') where user = 'root';
select host,user,password from user where user = 'root';
flush privileges;
quit;

This will perform updates on all the root passwords: i.e., for "localhost", "127.0.0.1", and "::1"

In the future, when I go to RHEL 8 or what have you, I will try to remember to check the /bin/mysql_secure_installation and see how the guys did it, who were the ones that configured MariaDB for this OS.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mike S
  • 1,235
  • 12
  • 19
3

Fix for macOS

  1. Install MySQL from https://downloads.mysql.com/archives/community/ (8.x is the latest as on date, but ensure that the version is compatible with the macOS version)

  2. Give password for root (let <root-password> be the password) during installation (don't forget to remember the password!)

  3. Select Use Legacy Password Encryption option (that is what I had used and did not try for Use Strong Password Encryption option)

  4. Search and open MySQL.prefPane (use search tool)

    1. Select Configuration tab
    2. Click Select option of Configuration File
      1. Select /private/etc/my.cnf
  5. From terminal open a new or existing file with name /etc/my.cnf (vi /etc/my.cnf) add the following content:

     [mysqld]
     skip-grant-tables
    
  6. Restart mysqld as follows:

    1. ps aux | grep mysql
    2. kill -9 <pid1> <pid2> ... (grab pids of all MySQL related processes)
  7. mysqld gets restarted automatically

  8. Verify that the option is set by running the following from terminal:

     ps aux | grep mysql
    
     > mysql/bin/mysqld ... --defaults-file=/private/etc/my.cnf ... (output)
    
  9. Run the following command to connect (let mysql-<version>-macos<version>-x86_64 be the folder where MySQL is installed. To grab the actual folder, run ls /usr/local/ and copy the folder name):

     /usr/local/mysql-<version>-macos<version>-x86_64/bin/mysql -uroot -p<root-password>
    
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BR M
  • 101
  • 7
  • The top answers are ALL BAD. To save hours of time use this answer - https://stackoverflow.com/a/58155034/4759176 – parsecer Dec 01 '20 at 01:32
  • I just copy pasted the solution that worked for me on Mac OS. I hope it is useful. I did not try this fix on Windows or Linux, other solutions I think should work for other OSs. – BR M Dec 02 '20 at 04:05
2

If you are like me and all the information in previous answers failed, proceed to uninstall all versions of MySQL on your machine, search for all remaining MySQL files using the command sudo find / -name "mysql" and rm -rf every file or directory with the "mysql" name attached to it (you should skip files related to programming language libraries).

Now install a fresh version of MySQL and enjoy. NB: You will lose all your data so weigh your options first.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
2

windows :

cd \Ampps\mysql\bin :

mysql.exe -u root -pmysql

after mysql start (you can see shell like this mysql> ) use this query :

 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';

try again access with root root

salvo720
  • 166
  • 1
  • 4
1

It can happen if you don't have enough privileges.

Type su, enter the root password and try again.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vitaly goji
  • 256
  • 4
  • 13
1

Sometimes a default password is set when you install it - as mentioned in the documentation. This can be confirmed by the following command.

sudo grep 'temporary password' /var/log/mysqld.log
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shivansh Jagga
  • 1,541
  • 1
  • 15
  • 24
1

After trying a lot with the following answer:

ALTER USER 'root'@'localhost' IDENTIFIED VIA mysql_native_password USING PASSWORD('root');

And similar answers, my terminal was still throwing me the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near...

So after researching on the web, this line solved my problem and let me change the root user password:

sudo mysqladmin --user=root password "[your password]"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Christian Leyva
  • 133
  • 2
  • 10
1

One thing to check is the from-host filter. It may be "localhost" by default. Are you trying to connect from a remote client? Change this to "%".

enter image description here

Jim Carnicelli
  • 179
  • 1
  • 7
0

If you reached this page via Google like I did and none of the previous solutions worked, what turned out to be the error was 100% foolishness on my end. I didn't connect to the server. Once connected everything was smooth sailing.

In case it helps to know my setup, I'm using Sequel Pro and am trying to connect to it with Node using the NPM package, mysql. I didn't think I needed to actually connect (other than run Sequel Pro), because I was doing that from my application already.

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mix Master Mike
  • 1,079
  • 17
  • 26
0

I was getting the same error while setting up the mysql-8 zip version. Finally, switched to installer version which worked seamlessly. During installation, there is a prompt to set up the root password. Once set, it works for sure.

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
amdg
  • 2,211
  • 1
  • 14
  • 25
0

According to MariaDB official documentation, in MariaDB 10.4.3 and later, the unix_socket authentication plugin is installed by default.

In order to disable it, and revert to the previous mysql_native_password authentication method, add line below in [mysqld] section of my.cnf file:

[mysqld]
unix_socket=OFF

And then run:

mysql_install_db --auth-root-authentication-method=normal

And then start mysqld

This command will then work fine:

mysqladmin -u root password CHANGEME

For additional information, see Configuring mysql_install_db to Revert to the Previous Authentication Method.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Fabrice Jammes
  • 2,275
  • 1
  • 26
  • 39
  • What is the unix_socket thingy supposed to do and why is this change necessary? Can you [add](https://stackoverflow.com/posts/66985012/edit) a little bit to your answer? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/66985012/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 21 '21 at 17:02
0

I was trying to leverage Docker desktop on Mac to get 5.7.35 running and this docker-compose.yml configuration allowed it to work:

In particular it was the addition of the line...

command: --default-authentication-plugin=mysql_native_password

...that did the trick

version: '3.3'
services:
  mysql_db:
    image: mysql:5.7
    command: --default-authentication-plugin=mysql_native_password
    restart: always
    environment:
      MYSQL_ROOT_PASSWORD: 'your_password'
    ports:
      - '3306:3306'
    expose:
      - '3306'
    volumes:
      - ~/your/volume/path:/var/lib/mysql
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
mjj1409
  • 3,075
  • 6
  • 28
  • 28
  • ***Why*** does that work? What is the explanation? Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/68623547/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Sep 21 '21 at 17:06
0

On Arch Linux

Package: mysql 8.0.29-1

What worked for me:

  1. Edit my.cnf file, normally can be found at /etc/mysql/my.cnf and append this skip-grant-tables at the bottom/end of the file.

  2. Restart mysql service by invoking sudo systemctl restart mysqld

  3. Ensuring mysql service has started properly by invoking sudo systemctl status mysqld

  4. Login to mysql using 'root' by invoking mysql -u root -p

  5. Flush privileges by invoking flush privileges;

  6. Create new user by CREATE USER 'root'@'localhost' IDENTIFIED BY 'rootpassword';

  7. (If you plan to use this db with PHP), you should instead use this CREATE USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'rootpassword';

  8. Check whether your changes have reflected in db by invoking the following in sequence:

    • use mysql;
    • SELECT User, password_last_changed FROM user;
  9. Exit mysql console and comment/remove skip-grant-tables by editing my.cnf file (Refer to step 1 for the location)

  10. Restart the mysql service (Refer to step 2 and step 3)

And that's all.

zep_ph
  • 11
  • 1
-1

The '-p' argument doesn't expect a space between the argument name and value.

Instead of

./mysqladmin -u root -p 'redacted'

Use

./mysqladmin -u root -p'redacted'

Or just

./mysqladmin -u root -p

which will prompt you for a password.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Grant Zvolsky
  • 483
  • 5
  • 6
-3

Solution: Give up!

Hear me out. I spent about two whole days trying to make MySQL work to no avail, always stuck with permission errors, none of which were fixed by the answers to this question. It got to the point that I thought if I continued I'd go insane.

Out of patience for making it work, I sent the command to install SQLite, only using 450 KB, and it worked perfectly right from the word go.

If you don't have the patience of a saint, go with SQLite and save yourself a lot of time, effort, pain, and storage space..!

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
VBW
  • 97
  • 10