The error returned was access denied for user

В статье описано, что за ошибка "Access denied for user 'root'@'localhost' (Using password: YES и NO)", каковы причины её появления, и как её исправить.

Ошибка: Access denied for user ‘root’@’localhost’ (Using password: YES и NO)

При работе с системой MySQL могут возникнуть самые разные ошибки, и на этапе освоения программы разобраться с ними может быть сложно. Одна из наиболее распространенных проблем — ошибка 1045, которая сопровождается сообщением Access denied for user ‘root’@’localhost’ (Using password: YES и NO). Сегодня я расскажу, как ее исправить.

Понять суть проблемы можно, переведя сообщение об ошибке на русский язык. Означает оно, что пользователю с именем root на машине localhost запрещен доступ к БД при использовании пароля или без него.

Окно Connection Error

Причины ошибки Access denied for user ‘root’@’localhost’

Чтобы свободно получить доступ в MySQL, должно совпасть три параметра, описывающих пользователя базы данных — имя, название машины и пароль. Если есть какие-то несовпадения, доступ будет запрещен. Самая простая причина проблемы — неправильный ввод пароля. Кроме этого, вызывать ошибку может неправильный синтаксис.

В системе MySQL нет простой зависимости имя пользователя – пароль, название хоста играет важную роль в получении доступа к БД. Оно может иметь вид IP-адреса, доменного имени, ключевого слова (например, localhost) или символа, объединяющего несколько машин в группу (например, % — любой хост, кроме локального).

Ошибка Access denied

Наиболее распространенные ошибки при обращении к БД:

  1. При присвоении прав новому пользователю не был указан адрес машины, с которой он может подключаться. В таком случае ему автоматически будет разрешено пользоваться БД с любого хоста, кроме локального, и при попытке подключения с localhost возникнет ошибка доступа.
  2. Неправильно расставленные кавычки. Если при создании пользователя написать ‘username@localhost’, это будет значить, что username@localhost может подключаться с любой машины, кроме локальной, а не что username может подключаться с компьютера localhost. Логин пользователя и имя машины должны иметь свою пару кавычек.
  3. Использование пароля при его отсутствии в базе данных.

В зависимости от того, при каком способе подключения к БД возникает ошибка Access denied for user ‘root’@’localhost’ (Using password: YES или NO), используются разные методы решения проблемы.

Если ошибка Access denied for user появляется с указанием Using password: YES, проблема заключается в неправильном вводе пароля. Проверить это можно, открыв таблицу mysql.user, в которой хранятся данные обо всех пользователях.

Таблица USE Mysql

Порядок действий таков:

  1. Откройте таблицу пользователей.
  2. Проверьте, существует ли пользователь root с хостом localhost. Если он есть, смотрите на поле «password». Если там пусто, зайти в базу можно без ввода пароля. Если там что-то есть, значит, вы вводите неправильный пароль.
  3. Смените пароль командой SET PASSWORD.
  4. Если пользователя root нет, создайте его, установите пароль и предоставьте ему права.

После этого в базу данных можно зайти. Если изменить данные не получается, следует использовать параметр —skip-grant-tables, который отменяет все настройки разрешений.

Файл конфигурации

Строки, которые нужно изменить в файле конфигурации

Если ошибка появляется с ключом (Using password: NO), нужно сделать следующее изменить файл config.inc.php, указав в нем правильные данные. Если проблема возникает при установке MySQL, нужно удалить базы данных старой версии программы или сменить пароль для доступа к ним, используя режим —skip-grant-tables.

Таким образом, ошибка Access denied for user ‘root’@’localhost’ (Using password: YES или NO) возникает при несоответствии пароля и имени пользователя и легко исправляется заменой данных для входа.

Опубликовано 06.06.2017 Обновлено 28.04.2021

Oops!! Frustrated with ‘Access denied for user ‘root’@’localhost’ (using password yes) in MySQL?

This error may occur due to many reasons which include insufficient privileges for the user to access the database, and when MySQL root password is wrong and so on.

At Bobcares, we often get requests to fix MySQL errors, as a part of our Server Management Services.

Today, let’s see how our Support Engineers fix this MySQL for our customers.

Why does access denied error occurs in MySQL?

This error may occur due to different reasons in different scenarios. Some of them are:

  • When a user who doesn’t exist on the MySQL server tries to access the database.
  • When there is no privilege for the user.
  • If the username or password is wrong.

Today, we’ll discuss in detail how we fix this Access denied for user ‘root’@’localhost’ (using password yes) in MySQL.

How we fix ‘access denied for user ‘root’@’localhost’ (using password yes) in MySQL’?

Let’s see, how we fix this access denied error for our customers in detail.

a. Not able to login

Recently, one of our customers approached us saying that he is getting an error like the one shown below while he is trying to log in to MySQL.

Access denied for user 'root'@'localhost' (using password yes) MySQL

So, our Support Engineers checked in detail and found that the root password is wrong. So, to reset the password we did the following:

1. Initially, we opened /etc/mysql/my.cnf

2. Then we added skip-grant-tables under [mysqld] section.

Here we skipped grant tables as there is no other way to log in.

By skipping the grant table option it allows anyone to log in from anywhere and can do anything on the database.

Note: skip-grant-tables is dangerous, so we will remove this at the end.

3 Then, we restarted the MySQL service using the command below:

service mysql restart

Now MySQL is configured to skip the grant-tables. So, we can log in now.

4. We logged into MySQL using:

mysql -u root 

5. Then, we flushed the privileges using:

Access denied for user 'root'@'localhost' (using password yes) MySQL

6. After that, we set a new password using the command below: UPDATE user SET

Password=PASSWORD('my_password') where USER='root';
FLUSH PRIVILEGES;

7. Then, we removed skip-grant-tables from /etc/mysql/my.cnf

8. Finally, we restarted the MySQL service and logged in to MySQL using the new password.

This fixes the error.

b. No global privilege

If there is no global privilege then this error can happen. In such cases, our Engineers add the privilege by:

GRANT ALL PRIVILEGES ON database.* TO 'user'@'localhost';

This fixes the error.

[Need more assistance to fix MySQL Error?- We’re available 24/7.]

Conclusion

In short, this error occurs mainly due to insufficient privileges to the user and can be fixed by granting the privilege. Also, today we discussed in detail how our Support Engineers fix this error for our customers.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

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.


 The_Ozon  
 05.09.2016  

 MySQL, Ламерские вопросы  
 3927

вопрос

Поставил я DLE 10.3 и тут ошибка MySQL

Переустановил DLE 3 раза и базу MySQL менял и опять то же самое.

Ответа пока нет


10 комментариев

Похожие вопросы

Последние события


  • События
  • Заказы
  • Модули
  • Фото dj-avtosh

    dj-avtosh
    Не подключается файл php через include в шаблоне .tpl ?
    Вчера, 18:13


    у хостера спросите

  • Фото alex2lp

    alex2lp
    Не подключается файл php через include в шаблоне .tpl ?
    Вчера, 16:51


    У меня в панели администрирования сайта есть такие логи: .error.log и .access.log

  • Фото dj-avtosh

    dj-avtosh
    Не подключается файл php через include в шаблоне .tpl ?
    Вчера, 16:48


    это не то, ищите FATAL-логи

  • Фото alex2lp

    alex2lp
    Не подключается файл php через include в шаблоне .tpl ?
    Вчера, 16:34


    [Thu Feb 09 10:08:23.724850 2023] [core:info] [pid 3549553] [client IP:PORT] AH00128: File does not exist: /var/www/user0/data/www/site.by/guru-include/public/css/style.css, referer:

    http://site.by/onlines.html

    [Thu Feb 09 10:08:23.731598 2023] [core:info] [pid 3529275] [client IP:PORT] AH00128: File does not exist: /var/www/user0/data/www/site.by/guru-include/public/js/app.js, referer:

    http://site.by/onlines.html

    [Thu Feb 09 10:08:23.734995 2023] [core:info] [pid 3544522] [client IP:PORT] AH00128: File does not exist: /var/www/user0/data/www/site.by/guru-include/public/js/scripts.js, referer:

    http://site.by/onlines.html

  • Фото dj-avtosh

    dj-avtosh
    Не подключается файл php через include в шаблоне .tpl ?
    Вчера, 14:20


    Никто не умеет гадать — смотрите в логи сервера почему 500

  • Фото Slavchik

    Slavchik
    Разрешения на BBcode по группам при добавлении новости с сайта — модуль GroupBBcode
    Вчера, 14:07


    del

  • Фото eXtErNaL

    eXtErNaL
    Сделать модуль для загрузки документов с электронной подписью
    8-02-2023, 18:19


  • Фото 1191

    1191
    Сделать модуль для загрузки документов с электронной подписью
    8-02-2023, 17:42


    Загружаются PDF файлы, они подписаны электронной подписью, в этой подписи есть все эти поля.

  • Фото lutskboy

    lutskboy
    Сделать модуль для загрузки документов с электронной подписью
    8-02-2023, 14:14


    суть модуля чтоб сделать уникальный ключ? все остальное имя фамилия дата откуда должно браться? дата с новости. фио с доп поля?

  • Фото FC1488SM

    FC1488SM
    Как сделать «Показать полностью», если текст больше N символов?
    8-02-2023, 08:37


    По поводу длины понял, есть проблема: тексты зависят от самого длинного текста, то есть если он увеличивается допустим на высоту 50px, то и другие тексты увеличиваются на столько же, как убрать эту зависимость элементов?

  • Сделать модуль для загрузки докум… 3
  • Парсер информации с кинопоиска 1
  • Лимит на скачивание файлов 2
  • Сделать чат с информером 0
  • В зависимости от страны пользоват… 5
  • Генерировать случайный уникальный… 0
  • У доп поля тип Список в некоторых… 1
  • DLE 13.2+ модуль вопрос-ответ 5
  • Добавление, редактирование новост… 0
  • DLE 14 + Сторонний php скрипт (+н… 2
  • Разрешения на BBcode по группам п… 1
  • Ajax search template 0
  • Index post 0
  • Extended category menu 0
  • Постраничная Ajax навигация для т… 0
  • Who rated | Список пользователей … 0
  • Who download | Список пользовател… 0
  • Защищенная ссылка для аттачментов… 0
  • DLE Dynamic xField 0
  • DLE xField Tab PRO 0

Понравилась статья? Поделить с друзьями:
  • The binding of isaac rebirth как изменить разрешение
  • The error report contains the following files
  • The beyond hub is currently unreachable some functionality will be unavailable как исправить
  • The battle for middle earth tm launcher error
  • The battle cats ошибка hgt00