Note: For MySQL 5.7+, please see the answer from Lahiru to this question. That contains more current information.
For MySQL < 5.7:
The default root password is blank (i.e., an empty string), not root
. So you can just log in as:
mysql -u root
You should obviously change your root password after installation:
mysqladmin -u root password [newpassword]
In most cases you should also set up individual user accounts before working extensively with the database as well.
answered Feb 21, 2014 at 20:54
Mike BrantMike Brant
69.9k10 gold badges97 silver badges103 bronze badges
15
I was able to solve this problem by executing this statement
sudo dpkg-reconfigure mysql-server-5.5
Which will change the root password.
answered Mar 18, 2014 at 3:37
8
I was recently faced with the same problem, but in my case, I remember my password quite alright, but it kept on giving me the same error. I tried so many solutions, but still none helped. Then I tried this:
mysql -u root -p
After which it asks you for a password like this
Enter password:
And then I typed in the password I used. That’s all.
answered Mar 21, 2018 at 22:22
XY-JOEXY-JOE
1,3641 gold badge10 silver badges8 bronze badges
3
You have to reset the password! Steps for Mac OS X (tested and working) and Ubuntu:
Stop MySQL using
sudo service mysql stop
or
sudo /usr/local/mysql/support-files/mysql.server stop
Start it in safe mode:
sudo mysqld_safe --skip-grant-tables --skip-networking
(the above line is the whole command)
This will be an ongoing command until the process is finished, so open another shell/terminal window, log in without a password:
mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
As per @IberoMedia’s comment, for newer versions of MySQL, the field is called authentication_string
:
mysql> UPDATE mysql.user SET authentication_string =PASSWORD('password') WHERE User='root';
Start MySQL using:
sudo service mysql start
or
sudo /usr/local/mysql/support-files/mysql.server start
Your new password is ‘password’.
Note: for version of MySQL > 5.7 try this:
update mysql.user set authentication_string='password' where user='root';
answered Sep 17, 2014 at 6:44
tk_tk_
15.8k8 gold badges80 silver badges89 bronze badges
12
It happens when your password is missing.
Steps to change the password when you have forgotten it:
-
Stop MySQL Server (on Linux):
sudo systemctl stop mysql
-
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 and run
mysql -u root
(as root). It will not ask for a password.If you get error like as below:
2018-02-12T08:57:39.826071Z mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists. mysql -u root ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) [1]+ Exit 1
-
Make MySQL service directory.
sudo mkdir /var/run/mysqld
Give MySQL user permission to write to the service directory.
sudo chown mysql: /var/run/mysqld
-
Run the same command in step 2 to run MySQL in background.
-
Run
mysql -u root
. You will get the MySQL console without entering a password.Run these commands
FLUSH PRIVILEGES;
For MySQL 5.7.6 and newer
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
For MySQL 5.7.5 and older
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
If the ALTER USER command doesn’t work use:
UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';
Now exit
-
To stop the instance started manually:
sudo kill `cat /var/run/mysqld/mysqld.pid`
-
Restart MySQL
sudo systemctl start mysql
answered Feb 12, 2018 at 14:25
4
At the initial start up of the server the following happens, given that the data directory of the server is empty:
- The server is initialized.
- SSL certificate and key files are generated in the data directory.
- The validate_password plugin is installed and enabled.
- The superuser account ‘root’@’localhost’ is created. The password for the superuser is set and stored in the error log file.
To reveal it, use the following command:
shell> sudo grep 'temporary password' /var/log/mysqld.log
Change the root password as soon as possible by logging in with the generated temporary password and set a custom password for the superuser account:
shell> mysql -u root -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass5!';
answered Mar 23, 2017 at 5:17
LahiruLahiru
1,33810 silver badges17 bronze badges
8
If the problem still exists, try to force changing the password:
/etc/init.d/mysql stop
mysqld_safe --skip-grant-tables &
mysql -u root
Set up a new MySQL root user password:
use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
flush privileges;
quit;
Stop the MySQL server:
/etc/init.d/mysql stop
Start the MySQL server and test it:
mysql -u root -p
answered May 20, 2014 at 13:34
Yasin HassanienYasin Hassanien
4,0051 gold badge20 silver badges16 bronze badges
6
If none of the other answers work for you, and you received this error:
mysqld_safe Logging to '/var/log/mysql/error.log'.
mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.
[1]+ Exit 1 sudo mysqld_safe --skip-grant-tables
Follow the below commands step by step until you reset your password:
# Stop your server first
sudo service mysql stop
# Make the MySQL service directory.
sudo mkdir /var/run/mysqld
# Give MySQL permission to work with the created directory
sudo chown mysql: /var/run/mysqld
# Start MySQL, without permission and network checking
sudo mysqld_safe --skip-grant-tables --skip-networking &
# Log in to your server without any password.
mysql -u root mysql
# Update the password for the root user:
UPDATE mysql.user SET authentication_string=PASSWORD('YourNewPasswordBuddy'), plugin='mysql_native_password' WHERE User='root' AND Host='localhost';
# If you omit (AND Host='localhost') section, it updates
# the root password regardless of its host
FLUSH PRIVILEGES;
EXIT;
# Kill the mysqld_safe process
sudo service mysql restart
# Now you can use your new password to log in to your server
mysql -u root -p
# Take note for remote access. You should create a remote
# user and then grant all privileges to that remote user
answered Apr 16, 2019 at 11:39
MehdiMehdi
3,7323 gold badges35 silver badges65 bronze badges
1
I came across this very annoying problem and found many answers that did not work. The best solution I came across was to completely uninstall MySQL and reinstall it. On reinstall you set a root password and this fixed the problem.
sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-5.5 mysql-client-core-5.5
sudo rm -rf /etc/mysql /var/lib/mysql
sudo apt-get autoremove
sudo apt-get autoclean
I found this code elsewhere, so I don’t take any credit for it. But it works. To install MySQL after uninstalling it, I think DigitalOcean has a good tutorial on it. Checkout my gist for this.
How to install MySQL on Ubuntu (which works)
answered Feb 9, 2017 at 21:05
JamesDJamesD
5815 silver badges10 bronze badges
0
I am using Ubuntu 16.04 (Xenial Xerus) and installed MySQL 5.7.
I had the same issue
Login denied for root user.
I tried the below steps:
-
dpkg --get-selections | grep mysql
(to get the version of MySQL). -
dpkg-reconfigure mysql-server-5.7
-
mysql -u root -p
Without -p that doesn’t prompt you to ask password. Once you are in, you can create a user with a password by following steps:
CREATE USER 'your_new_username'@'your-hostname' IDENTIFIED BY 'your-password';
GRANT ALL PRIVILEGES ON *.* to 'your_new_username'@'your-hostname' WITH GRANT OPTION;
Exit from the root and log in from the <name> you gave above.
mysql -u <your_new_username> -p
For some reason still just typing MySQL does not work. At all. I suggest to make it a habit to use mysql -u <name> -p
.
answered Jun 21, 2017 at 15:21
1
In the terminal, just enter:
mysql -u root -p
Then it will ask the password from you.
answered Jul 8, 2019 at 21:24
I installed MySQL as root user (
$SUDO
) and got this same issue
Here is how I fixed it:
-
sudo cat /etc/mysql/debian.cnf
This will show details as:
# Automatically generated for Debian scripts. DO NOT TOUCH! [client] host = localhost user = debian-sys-maint password = GUx0RblkD3sPhHL5 socket = /var/run/mysqld/mysqld.sock [mysql_upgrade] host = localhost user = debian-sys-maint password = GUx0RblkD3sPhHL5 socket = /var/run/mysqld/mysqld.sock
Above we can see the password. But we are just going to use
(GUx0RblkD3sPhHL5)
that in the prompt. -
`mysql -u debian-sys-maint -p
Enter password: `
Now provide the password (GUx0RblkD3sPhHL5).
-
Now
exit
from MySQL and log in again as:`mysql -u root -p
Enter password: `
Now provide the new password. That’s all. We have a new password for further uses.
It worked for me.
answered Sep 17, 2019 at 12:30
S.YadavS.Yadav
4,0353 gold badges35 silver badges42 bronze badges
For those for whom the current answers didn’t work can try this (tested on macOS):
mysql -h localhost -u root -p --protocol=TCP
After this, a password will be asked from you and you should use your OS user password. Then when you get into MySQL you can run:
select Host, User from mysql.user;
And you should see:
MySQL [(none)]> select Host, User from mysql.user;
+-----------+------------------+
| Host | User |
+-----------+------------------+
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------+------------------+
And from here you can change the configurations and edit the password or modify the grants.
answered Nov 25, 2020 at 19:29
EricEric
4406 silver badges15 bronze badges
1
Please read the official documentation: MySQL: How to Reset the Root Password
If you have access to a terminal:
MySQL 5.7.6 and later:
mysql
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
MySQL 5.7.5 and earlier:
mysql
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
answered Aug 10, 2015 at 10:05
d.danailovd.danailov
9,4364 gold badges50 silver badges36 bronze badges
2
I am using mysql-5.7.12-osx10.11-x86_64.dmg on Mac OS X.
The installation process automatically sets up a temporary password for the root user. You should save the password. The password can not be recovered.
Follow the instructions:
- Go to
cd /usr/local/mysql/bin/
- Enter the temporary password (which would look something like, «tsO07JF1=>3»)
- You should get the
mysql>
prompt. - Run,
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('{YOUR_PASSWORD}');
If you wish to set your password: «root» then the command would be,SET PASSWORD FOR 'root'@'localhost' = PASSWORD('root');
- Run
ALTER USER 'root'@'localhost' PASSWORD EXPIRE NEVER;
- Run
exit
- Run
./mysql -u root -p
- Type your password. In my case I would type, «root» (without quote)
- That’s all.
For convenience, you should add "/usr/local/mysql/bin"
to your PATH environment variable.
Now from anywhere you can type ./mysql -u root -p
and then type the password and you will get the mysql>
prompt.
answered May 30, 2016 at 11:14
tausiqtausiq
9271 gold badge13 silver badges23 bronze badges
The answer may sound silly, but after wasting hours of time, this is how I got it to work:
mysql -u root -p
I got the error message
ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: YES)
Even though I was typing the correct password (the temporary password you get when you first install MySQL).
I got it right when I typed in the password when the password prompt was blinking.
answered Dec 6, 2017 at 3:31
Amit KumarAmit Kumar
7342 gold badges9 silver badges16 bronze badges
1
If you have MySQL as part of a Docker image (say on port 6606) and an Ubuntu install (on port 3306) specifying the port is not enough:
mysql -u root -p -P 6606
will throw:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
as it’s trying to connect to localhost by default, specifying your local IP address fixes the issue:
mysql -u root -p -P 6606 -h 127.0.0.1
answered Nov 19, 2019 at 11:36
botrisbotris
1612 silver badges2 bronze badges
Year 2021.
Answer for Ubuntu 20.04 (Focal Fossa) (maybe other distributions as well).
After days of wandering around… and having none of those answers working for me, I did this and it worked!
Always in a Bash shell:
sudo systemctl disable mysql
In order to stop the daemon from starting on boot.
sudo apt purge mysql-server
and
sudo apt purge mysql-community-server*
There, it warns you you’ll erase configuration files… so it’s working! Because those are the ones making trouble!
sudo autoremove
To delete all the left behind packages.
Then (maybe it’s optional, but I did it) reboot.
Also, I downloaded mysql-server-8.0 from the official MySQL webpage:
sudo apt install mysql-server
A signal that it’s working is that when you enter the command above, the system asks you to enter the root password.
Finally:
mysql -u root -p
And the password you entered before.
answered Jul 26, 2021 at 3:48
DiegoMMFDiegoMMF
1091 silver badge3 bronze badges
If the problem still exists, try to force changing the password.
Stop MySQL Server (on Linux):
/etc/init.d/mysql stop
Stop MySQL Server (on Mac OS X):
mysql.server stop
Start the mysqld_safe daemon with —skip-grant-tables:
mysqld_safe --skip-grant-tables &
mysql -u root
Set up a new MySQL root user password:
use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
flush privileges;
quit;
Stop MySQL Server (on Linux):
/etc/init.d/mysql stop
Stop MySQL Server (on Mac OS X):
mysql.server stop
Start the MySQL server service and test to log in by root:
mysql -u root -p
answered Jul 26, 2017 at 2:19
Max YaoMax Yao
7116 silver badges7 bronze badges
I also came across the same problem. I did:
-
Open your cmd
-
Navigate to C:Program FilesMySQLMySQL Server 8.0bin>
(where MySQL Server 8.0 may be different depending on the server you installed) -
Then put the following command
mysql -u root -p
-
It will prompt for the password… simply hit Enter, as sometimes the password you entered while installing is changed by to blank.
Now you can simply access the database.
This solution worked for me on the Windows platform.
answered Nov 8, 2019 at 17:08
By default, the password will be null, so you have to change the password by doing the below steps.
Connect to MySQL
root# mysql
Use mysql
mysql> update user set password=PASSWORD('root') where User='root';
Finally, reload the privileges:
mysql> flush privileges;
mysql> quit
Just one line and it solved my issue.
sudo dpkg-reconfigure mysql-server-5.5
answered May 11, 2016 at 21:51
In Ubuntu 16.04 (Xenial Xerus) and MySQL version 5.7.13, I was able to resolve the problem with the steps below:
-
Follow the instructions from section B.5.3.2.2 Resetting the Root Password: Unix and Unix-Like Systems
MySQL 5.7 reference manual -
When I tried
#sudo mysqld_safe --init-file=/home/me/mysql-init &
it failed. The error was in /var/log/mysql/error.log:2016-08-10T11:41:20.421946Z 0 [Note] Execution of init_file '/home/me/mysql/mysql-init' started. 2016-08-10T11:41:20.422070Z 0 [ERROR] /usr/sbin/mysqld: File '/home/me/mysql/mysql-init' not found (Errcode: 13 - Permission denied) 2016-08-10T11:41:20.422096Z 0 [ERROR] Aborting
The file permission of mysql-init was not the problem. We need to edit AppArmor permissions.
-
Edit by
sudo vi /etc/apparmor.d/usr.sbin.mysqld
.... /var/log/mysql/ r, /var/log/mysql/** rw, # Allow user init file /home/pranab/mysql/* r, # Site-specific additions and overrides. See local/README for details. #include <local/usr.sbin.mysqld> }
-
Do
sudo /etc/init.d/apparmor reload
-
Start mysqld_safe again. Try step 2 above. Check file /var/log/mysql/error.log. Make sure there is no error and the mysqld is successfully started.
-
Run
mysql -u root -p
Enter password:
Enter the password that you specified in mysql-init. You should be able to log in as root now.
-
Shutdown mysqld_safe by
sudo mysqladmin -u root -p shutdown
-
Start mysqld the normal way by
sudo systemctl start mysql
answered Aug 10, 2016 at 13:37
codegencodegen
791 silver badge2 bronze badges
While the top answer (with mysqladmin) worked on macOS v10.15 (Catalina), it did not work on Ubuntu. Then I tried many of the other options, including a safe start for MySQL, but none worked.
Here is one that does:
At least for the version I got 5.7.28-0ubuntu0.18.04.4
answers were lacking IDENTIFIED WITH mysql_native_password
. 5.7.28 is the default on the current LTS and thus should be the default for most new new systems (till Ubuntu 20.04 (Focal Fossa) LTS comes out).
I found Can’t set root password MySQL Server and now applied
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_pass_here';
which does work.
answered Dec 9, 2019 at 10:43
arntgarntg
1,49714 silver badges12 bronze badges
The error that I faced was:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
It was a problem with the port running on.
By default, MySQL is running on port 3306.
You can check that on by running
-
in a 32-bit system:
sudo /opt/lampp/manager-linux.run
-
in a 64-bit system:
sudo /opt/lampp/manager-linux-x64.run
and click on the Configure button.
In my case the port was running on 3307, and I used the command
mysql -u root -p -P 3307 -h 127.0.0.1
answered Mar 12, 2020 at 16:20
RochaaPRochaaP
3056 silver badges14 bronze badges
Copied from this link, I had the same problem and this solved the problem. After we add a password for the database, we need to add -p
(password-based login), and then enter the password. Otherwise, it will return this error:
mysql -u root -p
answered Nov 5, 2020 at 8:07
Because your error message says «PASSWORD: YES» this means you are are using the wrong password. This happened to me also. Luckily I remembered my correct password, and was able to make the DB connection work.
answered May 31, 2022 at 22:17
In recent MySQL versions there isn’t any password
in the mysql.user
table.
So you need to execute ALTER USER
. Put this one line command into the file.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
And execute it as an init file (as the root or mysql user):
mysqld_safe --init-file=/home/me/mysql-init &
MySQL server need to be stopped to start mysqld_safe
.
Also, there may be a problem with AppArmor permissions to load this init file. Read more in AppArmor and MySQL.
answered Jun 9, 2016 at 15:06
If you haven’t set password yet, then run mysql -uroot
. It works for me.
answered Aug 16, 2018 at 11:10
ah bonah bon
8,9159 gold badges56 silver badges125 bronze badges
On Mac, if you have a problem in logging in with the first password you were given in installation, maybe you can just simply kill the MySQL process and then try.
So:
-
run the following command to find the PID of MySQL:
ps -aef | grep mysql | grep -v grep
-
kill the process:
kill -15 [process id]
Then you can log in with the initial password using this command:
mysql -uroot -p
Which asks you to enter your password. Just enter the initial password.
answered Jan 19, 2019 at 9:22
grep 'temporary password' /var/log/mysqld.log
Sort date (newest date)
You may see something like this;
[root@SERVER ~]# grep 'temporary password' /var/log/mysqld.log
2016-01-16T18:07:29.688164Z 1 [Note] A temporary password is generated for root@localhost: O,k5.marHfFu
2016-01-22T13:14:17.974391Z 1 [Note] A temporary password is generated for root@localhost: b5nvIu!jh6ql
2016-01-22T15:35:48.496812Z 1 [Note] A temporary password is generated for root@localhost: (B*=T!uWJ7ws
2016-01-22T15:52:21.088610Z 1 [Note] A temporary password is generated for root@localhost: %tJXK7sytMJV
2016-01-22T16:24:41.384205Z 1 [Note] A temporary password is generated for root@localhost: lslQDvgwr3/S
2016-01-22T22:11:24.772275Z 1 [Note] A temporary password is generated for root@localhost: S4u+J,Rce_0t
[root@SERVER ~]# mysql_secure_installation
Securing the MySQL server deployment.
Enter password for user root:
The existing password for the user account root has expired. Please set a new password.
New password:
Re-enter new password:
If you see it says
... Failed! Error: Your password does not satisfy the current policy requirements
That means your password needs to have a character such as ! . # - etc...
mix characters well, upper case, lower case, ! . , # etc...
New password:
Re-enter new password:
The 'validate_password' plugin is installed on the server.
The subsequent steps will run with the existing configuration
of the plugin.
Using existing password for root.
Estimated strength of the password: 100
Change the password for root ? ((Press y|Y for Yes, any other key for No) : Y
New password:
Re-enter new password:
Estimated strength of the password: 100
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL 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? (Press y|Y for Yes, any other key for No) : Y
Success.
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? (Press y|Y for Yes, any other key for No) : Y
Success.
By default, MySQL 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? (Press y|Y for Yes, any other key for No) : Y
- Dropping test database...
Success.
- Removing privileges on test database...
Success.
Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.
Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y
Success.
All done!
[root@SERVER ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 11
Server version: 5.7.10 MySQL Community Server (GPL)
Watch the last 10 minutes of this video, it teaches you how you do it.
This “access denied” error is one of the most common errors you’ll get when working with MySQL.
Learn how to fix it, and see a range of solutions if the suggested fix does not work, in this article.
When you try to connect to a MySQL database on your own computer (called “localhost”), you may get this error:
Access denied for user 'root'@'localhost' (using password: YES)
You might get an error code in front of it:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
You might also get the error with “using password no”:
Access denied for user 'root'@'localhost' (using password: NO)
You’ll see this if you log into MySQL using the command line:
mysql -u root -p
You might also see this if you log in to MySQL using an IDE such as MySQL Workbench. Or even if you use phpMyAdmin.
What does this mean? How can you fix it?
There are a few solutions to this, which I’ve detailed below. Try one, and if it doesn’t work, try another one.
Also a tip for logging in: don’t enter your password in the command line itself, because this will be stored in your command history. Use the -p option, as mentioned above, and then you’ll be prompted to enter the password.
Solution 1: Sudo then Change Password
If you get the “access denied” error, one way to solve it is by using sudo to log in to mysql and change the root password.
Step 1: Open the command line on your system.
Step 2: Open mysql using the sudo command:
sudo mysql
Step 3: Enter the password for this account.
Step 4: Change the auth_plugin to mysql_native_password, and the password for the root account, in a single command:
ALTER USER 'root'@'localhost'
IDENTIFIED WITH mysql_native_password BY 'your_new_password';
Substitute the word your_new_password with a new secure password that you want to use for the root account.
The mysql_native_password method is a traditional method of authentication and will allow you to login.
Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:
FLUSH PRIVILEGES;
Step 6: You can confirm that the new authentication method, or plugin, is used by selecting from the mysql.user table.
SELECT user, plugin
FROM mysql.user
Results:
user | plugin |
root | mysql_native_password |
Step 7: Exit the console by pressing CTRL + D or typing exit.
exit;
Step 8: Log in to mysql using the root account and the new password you set, which should work:
mysql -u root -p
You should now be logged in to the root account in mysql.
Solution 2: Edit My.cnf File
If the above solution did not work, you may need to edit the mysql.cnf file to allow for changes to the root account.
Step 1: Open the my.cnf file. This may be stored in:
/etc/my.cnf /etc/mysql/my.cnf
If you’re not sure where it is, search your MySQL installation folder (e.g. on Windows or Mac) for the file.
If you don’t have a my.cnf file (MacOS does not include one by default). You can create one in the /etc folder if you like.
Step 2: Add the word skip-grant-tables under the word [mysqld]. Your file may look like this:
[mysqld] skip-grant-tables
Step 3: Restart the MySQL server.
Step 4: Login to the root account:
mysql -u root -p
Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:
FLUSH PRIVILEGES;
Step 6: Set a new password for the account:
ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_new_password';
Substitute the word your_new_password with a new secure password that you want to use for the root account.
Step 7: Open the my.cnf file you opened in step 1, and remove the line about skip-grant-tables, and save the file.
Step 8: Restart the MySQL server again.
Step 9: Log in to the root account again:
mysql -u root -p
You should now be able to log in successfully with your new password and not get an error.
Conclusion
Either of these two solutions should hopefully solve the problem for you, and you should no longer get the error “Access denied for user ‘root’@’localhost’”.
If you have any questions, feel free to use the comments section below.
Стандарт / от Автора / 18.06.2022 / 2 комментария /
3 способа РЕШЕНИЯ по исправлению ошибки mysqli real connect (): (HY000/1045): Access denied for user ‘username’@’localhost’ на сервере Centos 7 и VestaCP
Ошибка mysqli real connect (): (HY000/1045): Access denied for user ‘username’@’localhost’ очень часто возникает при обновлении версии PHP на веб сервере или самой базы данных, особенно при использовании панели управления VestaCP.
Содержание:
Введение — ошибка mysql 1045
1 способ устранения ошибки mysql 1045
2 способ устранения ошибки mysql 1045
3 способ устранения ошибки mysql 1045
Заключение по устранению ошибки mysql 1045
Введение — ошибка mysql 1045
Прежде чем приступить к устранению данной ошибки, необходимо понять ряд элементарных вещей в работе базы данных MySQL.
Итак:
При создании пользователя базы данных MySQL учитывается 3 параметра, а не два. Первый параметр это username, имя пользователя базы данных, второй параметр, это имя хоста, под именем хоста подразумевается разрешение входа в базу, или с определенного IP адреса, или с определенного домена, или с любой машины кроме локальной, или только с локальной машины. Под локальной машиной подразумевается Ваш сервер, где расположена сама база данных и панель phpmyadmin.
Поясняю:
- Пользователь например, root@localhost имеет имя root, свой пароль и право входить только с локальной машины, то есть с Вашего сервера через командную строку или панель управления.
- Пользователь например, root@’мой домашний ip’ имеет имя root, свой пароль и право входить только с домашнего компьютера.
- Пользователь например, root@’%’ имеет имя root, свой пароль и право входить с любого компьютера, кроме локального, то есть Вашей панели управления веб сервером.
Знак ‘%’ в одинарных кавычках указывает именно на право входить в базу с любого компьютера, кроме локальной машины.
Пользователей с именем root может быть два, три и более. Все эти пользователи будут иметь разные пароли и разные разрешения на вход с определенных хостов.
1 способ устранения ошибки mysql 1045
Ошибка 1045
ERROR 1045 (28000): Access denied for user ‘ root’@’localhost’ (using password: YES)
Самая распространенная и банальная ошибка это неправильная пара логина и пароля для входа в БД. Грубо говоря, Вы можете пытаться входить под пользователем root@’%’, вводя правильный никнейм и пароль через установленную на сервере панель phpmyadmin. Но данный пользователь имеет право заходить с любого компьютера, кроме локальной машины. А панель phpmyadmin как раз является локальной машиной. Таким образом Вы будите получать данную ошибку.
Решение:
Самое простое, это попробовать ввести другой пароль от указанного пользователя. Но пароль может быть задан автоматически (в частности root), может быть пустым или просто утерянным.
Вам необходимо войти в MySQL через терминал в командной строке. Лично я использую программу putty, как и 99% администраторов веб сервера. Для того, чтобы попасть в БД, необходимо предварительно отредактировать конфигурационный файл под названием my.cnf. В операционной системе Centos 7 он находится /etc/my.cnf. Скачайте данный файл с сервера и вставьте в него после такую строку: skip-grant-tables, должно получится примерно так:
[mysqld]
skip-grant-tables
другие параметры
Залейте файл с новыми параметрами на сервер, предварительно удалив старый, а лучше просто переименуйте старый файл. Перезапустите сервер БД через Вашу панель управления.
После редактирования выше указанного файла попасть в MySQL можно без пароля со всеми привилегиями.
Теперь откройте терминал и войдите под пользователем root без пароля, введя команду:
sudo mysql -u root
Далее введите команду:
Если все сделали правильно, то будет показано вот такое окно:
SELECT user,host,password FROM mysql.user;
Из таблицы видно, что пользователя root вообще НЕ существует, однако после правки выше указанного конфига, я без труда вошел под root и без пароля. Так же видно из таблицы, что присутствуют 2 пользователя — admin с паролями и доступом с локальной машины (непосредственно с сервера через панель phpmyadmin) и с любого домашнего компьютера через терминал.
Этих пользователей я создавал сам и пароли от них я знаю. Исходя из полученной информации, я могу без труда войти в панель phpmyadmin. И создать любого необходимого пользователя с любыми привилегиями (правами).
Пользователь root отсутствует по причине удаления. Я его просто удалил для написания данной статьи. У вас он скорей всего присутствует и таблица будет гораздо шире. Это просто мой тестовый сервер для экспериментов.
Давайте посмотрим еще один пример с другого сервера.
По root у Вас будет примерно такая же картина. То есть один root имеет право войти в панель phpmyadmin с паролем. Один root имеет право на вход через терминал без пароля и т. д. Пароли в БД хранятся в зашифрованном виде.
Получив данную информацию, Вы сможете разобраться с доступами, найти необходимый пароль и войти в панель phpmyadmin.
НО увы, так бывает НЕ всегда!
2 способ устранения ошибки mysql 1045
Как уже писалось в начале статьи данная ошибка возникает после обновления ПО на сервере. И зачастую в панель phpmyadmin просто НЕ попасть. Если из первого раздела Вам не удалось разобраться с пользователями и паролями, то проще всего создать нового пользователя с правами администратора и войти в панель.
Выполнить это можно через терминал. Войдите на сервер через терминал с правами администратора и проверьте есть ли доступ без пароля. Как правило на сервере создается один пользователь root со входом без пароля из терминала. Введите команду:
sudo mysql -u root
Если на сервер баз данных попасть не удалось, то отредактируйте файл (my.cnf), как рассказано в первом способе и повторите команду:
sudo mysql -u root
Теперь, когда в БД удалось попасть через терминал, необходимо создать нового пользователя с паролем и правами админа. Команда:
CREATE USER 'root'@'localhost' IDENTIFIED BY 'ЗДЕСЬ ПАРОЛЬ';
Следующей командой предоставляются права администратора:
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;
После создания нового пользователя, как правило, можно под ним зайти в панель phpmyadmin. Это может быть совсем не обязательно пользователь root, а любой другой. Запомните имя пользователя и пароль, где то запишите себе. Лучше НЕ использовать root при создании нового пользователя.
Внимание!!! Не забудьте обратно отредактировать файл my.cnf, то есть удалить строку — skip-grant-tables.
3 способ устранения ошибки mysql 1045
Пожалуй, самый сложный способ, попытаюсь объяснить простым языком. Дело в том, что root пользователь создается по умолчанию. И если Вы начинаете играться с этим пользователем (root), то Вы нарушите пару логин — пароль. Так как пароль для этого пользователя создается и хранится в нескольких файлах на сервере.
Давайте поставим точку, рассмотрим все эти файлы и при необходимости зададим один пароль к данному юзеру.
Итак,
Файлов к счастью у нас не много, точнее три места которые необходимо проверить и поправить при необходимости.
-
Первое, открываем файл config.inc.php в Centos 7 находится /etc/phpmyadmin/config.inc.php В самый конец этого файла добавьте следующие строки кода:
/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = ' root';
$cfg['Servers'][$i]['controlpass'] = 'ЗДЕСЬ ПАРОЛЬ';
- Второе, в файле /usr/local/vesta/conf/mysql.conf. Я использую панель управления VestaCP, если у Вас другая панель, то расположение файла будет отличатся. Откройте данный файл и посмотрите какой там указан пароль, если нужно, то смените на Ваш.
- Третье, это непосредственно сама панель управления phpmyadmin.
Во всех трех местах, должны быть одинаковые пароли от этого юзера. Если не так, то исправляйте. В VestaCP при неправильных паролях в этих файлах может отвалится бэкап.
Заключение по устранению ошибки mysql 1045
Ошибка mysqli real connect 1045, как правило появляется при неправильной паре имя — пароль или после обновления ПО на сервере. Устраняется путем проверки пользователей через терминал и создания новых пользователей. В случаи не корректного пароля от root редактируются необходимые файлы.
P. S.
Я отлавливал все 3 причины сбоя панели управления phpmyadmin и данную статью публикую больше для себя как памятку по устранению неполадок. Но надеюсь Вам она тоже поможет. Оставляйте комментарии по решению данной проблемы.
Думаю, что теперь Вам не страшна ошибка mysqli_connect(): (HY000/1045): Access denied for user ‘username’@’localhost’.
Учебные материалы
Понравился материал? Подписывайтесь на наш блог. И получите бесплатный конструктор лендингов!
Только полезная информация и реальные кейсы
MySQL users often face an issue called Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes). This usually occurs when you enter an incorrect password or password for your database. Fixing these credentials can resolve this error in no time.
In this article, we will look at the ways to resolve this error.
How to fix “Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes)”?
The error looks something like this —
mysql -uroot -proot
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
It arises when you perform a fresh installation of MySQL and try to login with a password. The default password of MySQL is blank () (i.e. empty string).
So, you can login to the MySQL server using the same password.
Example
>mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or g.
Your MariaDB connection id is 9
Server version: 10.4.11-MariaDB mariadb.org binary distribution
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)]>
The best practice is to change the password after the new installation.
Set root user password
You must set the root user password after performing the new installation. Here is the code to set it –
Login as user root with blank password
>mysql -u root
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'abc';
Now the new password for root user is abc.
How to fix the Error 1045 (28000)?
Let us look at the ways to fix this problem –
-
Enter the correct credentials
The primary method to fix this error is to enter the correct username and password using the following command –
mysql –u username –p
-
Ensure the user is correct
Sometimes, the user you might be trying to access does not exist on the MySQL server. You can check if the user exists using the following code-
MariaDB [(none)]> select user from mysql.user where user like '%root%';
+------+
| User |
+------+
| root |
| root |
| root |
+------+
3 rows in set (0.001 sec)
If the user does not exist, create it with the desired username.
-
Enter the correct host name
You might be trying to access the server from a host that is different from the defined host name. You will encounter Error 1045 in this case. You can use this code to view details of the user –
To fix this, you can update the host name for the user using the code below –
mysql> mysql -u root -pabc -h <IP> -P 3306
You might encounter the error in due to the following scenarios –
Entered wrong password
>mysql -uroot -pssssss
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
Host doesn’t not have permission to connect database
This is a very common error that occurs while connecting to a remote database. While connecting to such a database we need to give access to the HOST IP ADDRESS to connect to it.
This is the IP Address of the source system which connects to the database server.
If access is not given, then run the given command –
CREATE USER ‘dbuser1’@'< Host IP >’ IDENTIFIED VIA mysql_native_password USING ‘***’;GRANT ALL PRIVILEGES ON *.* TO ‘dbuser1’@'< Host IP >’ REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;
Conclusion
Apart from all this, make sure the host contains the correct IP address and host name, to avoid the Error 1045 (28000) access denied for user ‘root’@’localhost’ (using password: yes).
Are you looking for a solution to fix the MySQL ERROR 1045 (28000): Access denied for user ‘user’@’localhost’ (using password: YES) error message?
If you’re an experienced MySQL database manager, you may have come across some vague and confusing problems, like MySQL Error 1045 (28000) messages. Fortunately, while resolving this error can be confusing at first due to its many potential causes, its solutions tend to be relatively simple. Once you determine the reason behind the database error you’re seeing, you should be able to fix it fairly quickly.
In this post, we’ll cover the various possible causes of the MySQL Error 1045 (28000). Then we’ll share solutions for each common situation, to help you get your database and your site back up and running.
Why the MySQL Error 1045 (28000) Error Occurs
The MySQL Error 1045 (28000) is an authentication error. «MySQL ERROR 1045 (28000): Access denied for user ‘user’@’localhost’ (using password: YES)» typically indicates that MySQL cannot log you in using the username and password you’ve specified.
This usually occurs when you provide an incorrect username/password combination when making the database connection. However, there are many other different situations that can lead to this type of behaviour.
- Connecting to the wrong host or port
- Provided user does not exist
- User does exist but client host have insufficient permission to connect, or be IP banned
- Wrong password provided
- Bash converts special characters in the password to a different encoding
Wrong host or port
If you don’t specify the host to connect (with the -h
flag), MySQL client will try to automatically connect to the localhost
instance. You may be trying to connect to another host/port instance. In this case, simply add -h
flag followed by the hostname you’re trying to connect to.
Code language: HTML, XML (xml)
Also, double check if you are trying to connect to the right port. MySQL, by default, listen on port 3306, but different setups use different ports for security purposes. Providing -P
flag and a port number in the command is a great way to remind you of this detail.
Code language: HTML, XML (xml)
[[email protected]]# mysql -u root -psekret -h <IP_or_hostname> -P 3306
Provided user does not exist
MySQL stores user data in a table called user
in a database named mysql
(by default). The following query will return 1
if a user with the specified username exists, 0
otherwise.
Code language: JavaScript (javascript)
mysql> SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'username') Query OK, 0 rows affected (0.00 sec)
If the user does not exist, you can create a new user:
Code language: JavaScript (javascript)
mysql> CREATE USER 'username'@'localhost' IDENTIFIED BY 'password'; Query OK, 0 rows affected (0.00 sec)
Client host have insufficient permission
By default, the MySQL server listens for connections only from localhost, which means it can be accessed only by applications running on the same host.
Remote root
access is disabled by default. If you want to enable that, run this SQL command locally:
Code language: JavaScript (javascript)
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;
And then find the following line and comment it out in your my.cnf
file, which usually lives on /etc/mysql/my.cnf
on Unix/OSX systems. In some cases the location for the file is /etc/mysql/mysql.conf.d/mysqld.cnf
).
Alternatively, you can check to see which host user/host MySQL allows connections with the following query:
Code language: JavaScript (javascript)
mysql> SELECT Host, User FROM mysql.user WHERE User='user01'; +-------------+-------------+ | Host | User | +-------------+-------------+ | 192.168.0.1 | user01 | +-------------+-------------+ 1 row in set (0.00 sec)
Wrong password provided
This is by far the most common reason for MySQL ERROR 1045 (28000): Access denied for user ‘user’@’localhost’ (using password: YES).
MySQL lists user accounts in the user
table of the mysql
database. Each MySQL account can be assigned a password, although the user
table does not store the cleartext version of the password, but a hash value computed from it.
You cannot read user passwords in plain text from MySQL as the password hash is used for authentication, but if you can get into MySQL command line interface (with root privileges), you can compare what you remember with the hashed value with “PASSWORD” function with the command below.
Code language: JavaScript (javascript)
mysql> SELECT Host, User, authentication_string, PASSWORD('forgotten') FROM mysql.user WHERE User='nonexistant'; +-------------+-------------+-------------------------------------------+-------------------------------------------+ | Host | User | authentication_string | PASSWORD('forgotten') | +-------------+-------------+-------------------------------------------+-------------------------------------------+ | 192.168.0.1 | nonexistant | *AF9E01EA8519CE58E3739F4034EFD3D6B4CA6324 | *70F9DD10B4688C7F12E8ED6C26C6ABBD9D9C7A41 | | % | nonexistant | *AF9E01EA8519CE58E3739F4034EFD3D6B4CA6324 | *70F9DD10B4688C7F12E8ED6C26C6ABBD9D9C7A41 | +-------------+-------------+-------------------------------------------+-------------------------------------------+ 2 rows in set, 1 warning (0.00 sec)
From the output, we can clearly see that the hashed value for ‘forgotten’ does not match the authentication_string column, which means ‘forgotten’ is the wrong password.
Executing the following query will overwrite the current password with a new one :
Code language: PHP (php)
mysql> set password for 'nonexistant'@'%' = 'helloworld'; Empty set (0.00 sec)
Special characters in the password
If you’re using Bash as your main shell, you should know that not all characters are treated equal in Bash. Some characters are evaluated by Bash to have a non-literal meaning. Instead, these characters carry out a special instruction, or have an alternate meaning; they are called «special characters», or «meta-characters».
In this case, your password contains some of the those special characters which might be mistakenly converted to another form by Bash. To prevent this from happening, wrap your password in single quotes in the command:
Code language: PHP (php)
[[email protected]]# mysql -u user01 -p'hello$!*&^%$#@!' mysql: [Warning] Using a password on the command line interface can be insecure ... mysql>
Regain access to the database
If you’re locked out and need to bypass the authentication mechanisms to regain access to the database, here are simple steps to do so. Please note that we’re using MariaDB to demonstrate the steps.
- Stop the instance by running
sudo systemctl stop mariadb
- Use
mysqld_safe
to start mysqld server by running the command:mysqld_ safe –user=mysql –skip-grant-tables –skip-networking
- Now you can open up a new terminal and access the MySQL server instance with
root
privileges by runningmysql -u root -h localhost
. - Please do note that since we’re running
grant-skip-tables
, any GRANT/CREATE/SET PASSWORD statements won’t work straight away. In order to fix this, run FLUSH PRIVILEGES;. - Run
SET PASSWORD FOR 'root'@'localhost' = '[email protected]!'
to change the password forroot
user. - Alternatively, you can modify
mysql.users
table with a query which modifies the password for User and Host like UPDATE mysql.user SET authentication_string=PASSWORD(‘newpwd’) WHERE User=’root’ and Host=’localhost’; - Stop the
mysqld_safe
instance and restart MySQL again fromsystemctl
. - You should be able to login with
root
from the localhost with the new password and do any other necessary corrective operations with root user.
Если вы захотите настроить резервное копирование базы данных на другой сервер, или протестировать соединение с базой данных из другого сервера. И тогда вы можете столкнуться с ошибкой access denied for user root localhost, даже если вы указали верное имя пользователя, базу данных и пароль.
В этой небольшой статье мы рассмотрим почему возникает эта ошибка, а также как ее исправить и подключиться к MySQL из другого сервера через интернет.
Если переводить дословно, то эта ошибка означает что у вас нет доступа к данной базе данных от имени этого пользователя. В примере я использовал пользователя root, но вы можете использовать и другого пользователя. Это может быть вызвано несколькими причинами:
- Пароль введен неверно;
- По каким-либо причинам у пользователя нет прав на доступ к базе данных;
- В настройках этого пользователя запрещено авторизоваться с этого сервера;
Для безопасности базы данных в mysql была придумана настройка хоста, из которого пользователь может авторизоваться. По умолчанию для пользователей устанавливается разрешение на авторизацию только с localhost. Чтобы разрешить подключение с других хостов, нужно менять настройки. Рассмотрим как это делается с помощью Phpmyadmin и в терминале.
Исправляем ошибку access denied for user root localhost
1. Подключение с другого хоста
Сначала рассмотрим как работать с Phpmyadmin. Это намного проще для начинающих и тех, кто не любит работать в терминале. Откройте Phpmyadmin, авторизуйтесь в программе с правами root и перейдите на вкладку «Учетные записи пользователей»:
Здесь, вы увидите, кроме обычных полей, поле «имя хоста», которое указывает с какого хоста может подключаться пользователь. Если в этом поле написано localhost, значит этот пользователь может авторизоваться только с локальной машины. Также, в этом поле может находиться IP адрес, с которого есть разрешение или символ %, который означает, что пользователь может подключаться с любого IP.
Чтобы изменить права для пользователя, нужно нажать на ссылку «Редактировать привилегии» для него, на открывшейся странице перейдите на вкладку «Информация об учетной записи»:
Затем установите в поле «Имя хоста» значение «Любой хост» чтобы разрешить этому пользователю авторизоваться с любого IP. Если вы хотите разрешить только определенный IP, выберите «Использовать текстовое поле» и укажите нужный адрес или подсеть:
После этого останется нажать кнопку «Вперед» чтобы сохранить настройки. Если вам нужно чтобы был доступ и с локального IP, и с другого, то необходимо создать еще одного пользователя. После этого вы сможете авторизоваться от имени этого пользователя.
Теперь рассмотрим другой способ решить ошибку 1045 access denied for user root localhost, с помощью терминала. Это немного проще, поскольку вам нужно только выполнить несколько команд:
mysql
> UPDATE mysql.user SET Host='%' WHERE Host='localhost' AND User='имя_пользователя';
> UPDATE mysql.db SET Host='%' WHERE Host='localhost' AND User='имя_пользователя';
> FLUSH PRIVILEGES;
Уже после этого, вы можете подключаться к серверу баз данных с любого другого компьютера и не получите никаких ошибок. Вместо символа %, можно указать нужный ip или localhost, если ограничение нужно вернуть обратно.
2. Неверный пароль root
Иногда случается, что при установке базы данных пароль для root задается, но вы его не знаете. Поскольку это главный пользователь и если вы не можете войти от его имени, то вы не сможете ничего исправить. Сначала попробуйте авторизоваться от имени root в системе и подключиться к базе без пароля:
mysql
Иногда это работает. Если не сработало, остановите службу mysql и запустите ее без проверки безопасности, а затем попробуйте снова:
systemctl stop mysqld
mysqld --skip-grant-tables
mysql
> USE mysql;
> UPDATE user SET Password=PASSWORD('ваш_пароль') where USER='root';
> FLUSH PRIVILEGES;
Еще можно попытаться выдать права над всеми таблицами нашему пользователю, если это необходимо:
> GRANT ALL ON *.* TO 'root'@'localhost' WITH GRANT OPTION;
Обратите внимание на хост localhost, если вы хотите чтобы удаленные узлы тоже могли подключаться к этому пользователю, то нужно использовать %. Дальше можно перезапустить базу данных и работать как обычно.
Выводы
Теперь вы знаете как решается mysql access denied for user root localhost и что делать в таких ситуациях, чтобы решить проблему. Надеюсь, эта информация была полезной для вас. Если у вас остались вопросы, спрашивайте в комментариях!
https://youtu.be/avnitMoiJww
Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .
Об авторе
Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.