Mysql2 error connectionerror access denied for user root localhost using password no

Если вы захотите настроить резервное копирование базы данных на другой сервер, или протестировать соединение с базой данных из другого сервера. И тогда вы

Если вы захотите настроить резервное копирование базы данных на другой сервер, или протестировать соединение с базой данных из другого сервера. И тогда вы можете столкнуться с ошибкой 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 License

Статья распространяется под лицензией Creative Commons ShareAlike 4.0 при копировании материала ссылка на источник обязательна .

Об авторе

Основатель и администратор сайта losst.ru, увлекаюсь открытым программным обеспечением и операционной системой Linux. В качестве основной ОС сейчас использую Ubuntu. Кроме Linux, интересуюсь всем, что связано с информационными технологиями и современной наукой.

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.

In mysql, Access denied for user ‘root’@’localhost’ error is due to the root user not having sufficient privilege to access the database. Either the root user password is incorrect, or the root user password is not set, or the root user has insufficient privileges.

In mysql, “access denied for user ‘root’@’localhost’ (using password: yes)” error is shown while the access denied for user root localhost using password yes. In mysql, “access denied for user ‘root’@’localhost’ (using password: no)” error is shown while the access denied for user root localhost using password no.

In mysql, if you attempt to access the root password, it throws error saying “Access denied for user ‘root’@’localhost’”. This exception is due to various reasons. Here we can see how this error is handled and how to correct it.

All the privileges should be granted to root user. By default, mysql does not provide the root user with all of the privileges. These privileges should be added to the root user.

If the root user has trouble logging in, the error below will appear in mysql 

Access denied for user ‘root’@’localhost’
access denied for user ‘root’@’localhost’ (using password yes)
access denied for user ‘root’@’localhost’ (using password no)
access denied for user ‘root’@’localhost’ (using password: yes)
access denied for user ‘root’@’localhost’ (using password: no)
access denied for user ”@’localhost’ (using password: no)
access denied for user @’localhost’ (using password: no)

Root cause

You try to connect mysql using root user. Mysql denied access to login with root user. The denial could be due to various reason. Mysql requires valid user name and password to login. The user must have enough privileges to login and should be provided with enough permission.

The above error will be thrown due to any of the above reason is not satisfied. The root password is mismatch or nor provided. The user does not have enough permission to login to the system.

How to reproduce this issue

This error occurs under various conditions.This error will be seen if you login with root user without password. It is a easy way of creating this error. There are various ways to replicate this error.

mysql -u root 

Solution 1

The first option is to use the command below to attempt login with username and correct password. This command will prompt you to enter your password. Enter the right password. Mysql will validate the username and password. If both are matching with the existing system, then mysql will allow to login. The error “Access denied for user ‘root’@’localhost’” is thrown due to the invalid password.

$>mysql -u root -p 
Enter password:

Solution 2

If you have forgotten the root user, the following steps will help you to update your root password. The root user will be modified in PASSWORD() function with the provided password. The password is set as “password” in the example below. This step will allow to reset the root user password.

$> mysqld --skip-grant-tables

$> mysql -u root mysql

mysql> update mysql.user set password=PASSWORD("password") where User='root';

mysql> flush privileges;

Solution 3

By default, the root user will not have a plugin attached. Update the root user with the plugin ‘ mysql native password ‘ This plugin ‘ mysql native password ‘ allows native authentication. For any command, the error “Access denied for user ‘root’@’localhost’” is shown if the mysql native password plugin is not set to the root user.

$> mysqld --skip-grant-tables

$> mysql -u root mysql

mysql> update mysql.user set plugin = 'mysql_native_password' where User='root';

mysql> flush privileges;

Solution 4

The password of the root user and the plugin must be changed. The alter command will change the password of the root user and update the plugin as “mysql native password.” The plugin stores a password in a native format and allows native authentication.

$> mysqld --skip-grant-tables

$> mysql -u root mysql

mysql> ALTER mysql.user 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

mysql> FLUSH PRIVILEGES;

mysql> exit

start mysql again

Solution 5

The root user has the admin privileges. Provide all permissions for the root user to connect from the local system. The grant command will add the privileges to the root command. If you want to revert the privilege, use the ‘revoke’ command. The ‘revoke’ command will remove the privileges from the user.

mysql> CREATE USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
        or
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

mysql> grant all privileges on *.* to 'root'@'localhost' identified by 'password' with grant option;

mysql> FLUSH PRIVILEGES;

Понравилась статья? Поделить с друзьями:
  • Mysql таблица используется ошибка
  • Mysql ошибка при импорте
  • Mysql ошибка 2013
  • Mysql ошибка 2006
  • Mysql ошибка 2002