Mysql connect error access denied for user bitrix localhost using password yes

Есть и-нет магазин, сделал резервную копию базы данных и директории /homeПеренес её на др. сервер (виртуальная машина битрикс) ip 192.168.0.80При обращении из браузера по адресу 192.168.0.80 выдает ошибку (см. текст ниже)Куда копать? Какие файлы редактировать?[BitrixMainDBConnectionException] Mysql connect error [localhost, 127.0.0.1]: Access denied for user 'bitrix'@'localhost' (using password: YES) (400)/home/bitrix/www/bitrix/modules/main/lib/db/mysqlconnection.php:43#0:...
 

Пользователь 235213

Заглянувший

Сообщений: 16
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 04.07.2015

Есть и-нет магазин, сделал резервную копию базы данных и директории /home
Перенес её на др. сервер (виртуальная машина битрикс) ip 192.168.0.80
При обращении из браузера по адресу 192.168.0.80 выдает ошибку (см. текст ниже)
Куда копать? Какие файлы редактировать?

[BitrixMainDBConnectionException]
Mysql connect error [localhost, 127.0.0.1]: Access denied for user ‘bitrix’@’localhost’ (using password: YES) (400)
/home/bitrix/www/bitrix/modules/main/lib/db/mysqlconnection.php:43
#0: BitrixMainDBMysqlConnection->connectInternal()
              /home/bitrix/www/bitrix/modules/main/lib/db/mysqlconnection.php:91
#1: BitrixMainDBMysqlConnection->queryInternal(string, array, NULL)
              /home/bitrix/www/bitrix/modules/main/lib/db/connection.php:332
#2: BitrixMainDBConnection->query(string)
              /home/bitrix/www/bitrix/modules/main/lib/config/option.php:150
#3: BitrixMainConfigOption::load(string, NULL)
              /home/bitrix/www/bitrix/modules/main/lib/config/option.php:36
#4: BitrixMainConfigOption::get(string, string, string)
              /home/bitrix/www/bitrix/modules/main/lib/httprequest.php:323
#5: BitrixMainHttpRequest->prepareCookie(array)
              /home/bitrix/www/bitrix/modules/main/lib/httprequest.php:63
#6: BitrixMainHttpRequest->__construct(object, array, array, array, array)
              /home/bitrix/www/bitrix/modules/main/lib/httpapplication.php:43
#7: BitrixMainHttpApplication->initializeContext(array)
              /home/bitrix/www/bitrix/modules/main/lib/application.php:122
#8: BitrixMainApplication->initializeExtendedKernel(array)
              /home/bitrix/www/bitrix/modules/main/include.php:24
#9: require_once(string)
              /home/bitrix/www/bitrix/modules/main/include/prolog_before.php:14
#10: require_once(string)
              /home/bitrix/www/bitrix/modules/main/include/prolog.php:10
#11: require_once(string)
              /home/bitrix/www/bitrix/header.php:1
#12: require(string)
              /home/bitrix/www/index.php:3

 

Пользователь 222975

Постоянный посетитель

Сообщений: 173
Баллов: 17
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 30.10.2013

Проверьте доступы к БД в /bitrix/php_interface/dbconn.php и /bitrix/.settings.php

 

Пользователь 235213

Заглянувший

Сообщений: 16
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 04.07.2015

#3

1

23.07.2015 16:58:07

Цитата
Андрей Сёмин написал:
Проверьте доступы к БД в /bitrix/php_interface/dbconn.php и /bitrix/.settings.php

Спасибо! Помогло!
Столько времени убил, а все было так просто!

 

Пользователь 356990

Заглянувший

Сообщений: 9
Авторитет:

2

Рейтинг пользователя:

0

Регистрация: 06.07.2015

 

Пользователь 863

Постоянный посетитель

Сообщений: 242
Баллов: 29
Авторитет:

1

Рейтинг пользователя:

2

Регистрация: 21.10.2004

А мне вот не помогло — ошибка начала валиться посредине ночи на работающем сервере, с момента каких-либо изменений прошло минимум 12 часов. Пароль на БД менять пытался (как и убирать), сервер перезапускал. Не помогает. Какие еще есть варианты решения?

Когда-то наблюдал такую проблему, она лечилась откатом на предыдущую версию БУС (т.е. была какая-то бага в БУС-е, которую потом исправили с очередным обновлением). Теперь что, интересно… И почему код 15-ой или какой там версии БУС-а в этом случае допускает примитивную необработанную ошибку, и заставляет гадать о причинах?

Upd: нашелся пароль в .settings.php . А кто-нибудь может обьяснить, зачем дублировать информацию о настройках соединения к БД в двух разных файлах в разных каталогах?

С уважением,
Евгений Маевский

 

Пользователь 136059

Гуру

Сообщений: 5418
Баллов: 636
Авторитет:

22

Рейтинг пользователя:

0

Регистрация: 16.07.2012

#6

2

26.09.2016 17:39:37

Цитата
eldos написал:
А кто-нибудь может обьяснить, зачем дублировать информацию о настройках соединения к БД в двух разных файлах в разных каталогах?

Для совместимости. .settings.php это от нового ядра d7, dbconn.php для старого.

Голосуй за идеи по развитию API Bitrix:
https://idea.1c-bitrix.ru/26707/
https://idea.1c-bitrix.ru/26709/
https://idea.1c-bitrix.ru/the-local-extension-folder-js/

 

Пользователь 312252

Заглянувший

Сообщений: 8
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 12.02.2015

#7

0

21.02.2018 08:12:20

Цитата
eldos написал:
А мне вот не помогло — ошибка начала валиться посредине ночи на работающем сервере, с момента каких-либо изменений прошло минимум 12 часов. Пароль на БД менять пытался (как и убирать), сервер перезапускал. Не помогает. Какие еще есть варианты решения?

Когда-то наблюдал такую проблему, она лечилась откатом на предыдущую версию БУС (т.е. была какая-то бага в БУС-е, которую потом исправили с очередным обновлением). Теперь что, интересно… И почему код 15-ой или какой там версии БУС-а в этом случае допускает примитивную необработанную ошибку, и заставляет гадать о причинах?

Upd: нашелся пароль в .settings.php . А кто-нибудь может обьяснить, зачем дублировать информацию о настройках соединения к БД в двух разных файлах в разных каталогах?

Я столкнулся с той же проблемой, Техподдержка вежливо послала нас

в

 к золотым партнерам.
Скажите как вы решили проблему?

 

Пользователь 312252

Заглянувший

Сообщений: 8
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 12.02.2015

Присоединяюсь к вопросу, ибо Техподдержка послали меня на… поиски платных решений этой проблемы.

 

x-com.kz, проверьте данные доступа к СУБД. Попробуйте залогиниться из консоли

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#10

0

23.05.2018 12:49:48

Цитата
Андрей Николаев написал:
x-com.kz , проверьте данные доступа к СУБД. Попробуйте залогиниться из консоли

Столкнулся с такой же проблемой. Чекнул базу, перегружал, доступы указаны верно и залогинка проходит нормально, базу видит.
Что может быть ещё не так ?

 

#11

0

23.05.2018 14:11:30

Николай Свистов, root@localhost и root@127.0.0.1 это разные пользователи.
P.S. При проверке подключения из консоли обязательно указывайте хост иначе не поймете в чем проблема.

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#12

0

23.05.2018 14:34:43

Цитата
Андрей Николаев написал:
Николай Свистов , root@localhost и root@127.0.0.1 это разные пользователи.
P.S. При проверке подключения из консоли обязательно указывайте хост иначе не поймете в чем проблема.

Ошибка

Скрытый текст

Код
array (
      'default' =>
      array (
        'className' => '\Bitrix\Main\DB\MysqlConnection',
        'host' => 'localhost',
        'database' => 'bx-portal',
        'login' => 'bxuser',
        'password' => 'secretpass',
        'options' => 2,
      ),
    ),
    'readonly' => true,
  ),
 

dbconn.php

Код
$DBType = "mysql";
$DBHost = "localhost";
$DBLogin = 'bxuser';
$DBPassword = 'secretpass';
$DBName = "bx-portal";
$DBDebug = false;
$DBDebugToFile = false;
define("MYSQL_TABLE_TYPE", "INNODB");

подключение тестирую таким образом

Код
mysql -ubxuser -psecretpass -h localhost
 

Пользователь 136059

Гуру

Сообщений: 5418
Баллов: 636
Авторитет:

22

Рейтинг пользователя:

0

Регистрация: 16.07.2012

#13

0

23.05.2018 15:11:07

Цитата
Николай Свистов написал:
Mysql connect error [localhost, 127.0.0.1]: No such file or directory (400)

У Вас другая ошибка (не как у автора). Проверьте mysql, скорее всего сокет упал. Перезагрузите и ищите в логах причину паения

Голосуй за идеи по развитию API Bitrix:
https://idea.1c-bitrix.ru/26707/
https://idea.1c-bitrix.ru/26709/
https://idea.1c-bitrix.ru/the-local-extension-folder-js/

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#14

0

23.05.2018 15:27:45

Цитата
Андрей Николаев написал:

Цитата
Николай Свистов  написал:
Mysql connect error [localhost, 127.0.0.1]: No such file or directory (400)

У Вас другая ошибка (не как у автора). Проверьте mysql, скорее всего сокет упал. Перезагрузите и ищите в логах причину паения

Сокет на месте и ошибок нет

 

Пользователь 1313397

Посетитель

Сообщений: 70
Баллов: 7
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 07.08.2017

#15

0

23.05.2018 16:30:44

Цитата
Николай Свистов написал:

Цитата
Андрей Николаев  написал:

Цитата
Николай Свистов  написал:
Mysql connect error [localhost, 127.0.0.1]: No such file or directory (400)

У Вас другая ошибка (не как у автора). Проверьте mysql, скорее всего сокет упал. Перезагрузите и ищите в логах причину паения

Сокет на месте и ошибок нет

Ошибка указывает на отсутствие соединения к БД и, в том числе, нету какой-то директории….проверяйте свой сервак

 

Пользователь 136059

Гуру

Сообщений: 5418
Баллов: 636
Авторитет:

22

Рейтинг пользователя:

0

Регистрация: 16.07.2012

#16

0

23.05.2018 17:40:29

Цитата
Николай Свистов написал:
Сокет на месте и ошибок нет

То что он на месте, не значит что он «правильный». Перезагрузите mysqld и попробуйте подключаться на 127.0.0.1

Голосуй за идеи по развитию API Bitrix:
https://idea.1c-bitrix.ru/26707/
https://idea.1c-bitrix.ru/26709/
https://idea.1c-bitrix.ru/the-local-extension-folder-js/

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#17

0

24.05.2018 08:35:33

Цитата
Андрей Николаев написал:

Цитата
Николай Свистов  написал:
Сокет на месте и ошибок нет

То что он на месте, не значит что он «правильный». Перезагрузите mysqld и попробуйте подключаться на 127.0.0.1

На 127.0.0.1 не подключается. Но в файлах конфигурации указано «localhost» , почему оно должно подключаться на 127.0.0.1 ?
Я создал пользователя в ДБ

bxuser@127.0.0.1

Так же я в интернете натыкался на статью, что в новой версии портала, сменился дефолтный порт с 3306 на 13306 (если я не ошибаюсь), это так?

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#18

0

24.05.2018 08:37:44

Цитата
Vladislav S. написал:
Ошибка указывает на отсутствие соединения к БД и, в том числе, нету какой-то директории….проверяйте свой сервак

Сделал чек БД и ошибка сменилась на следующую

Код
FILE: /home/bitrix/www/bitrix/modules/main/classes/mysql/main.php
 LINE: 99
MySQL
 Query Error: SEL ECT L.*, L.LID as ID, L.LID as SITE_ID,    C.FORMAT_DATE,
 C.FORMAT_DATETIME, C.FORMAT_NAME, C.WEEK_START, C.CHARSET, C.DIRECTION 
FR OM b_lang L, b_culture C WHERE C.ID=L.CULTURE_ID AND L.ACTIVE='Y' 
ORDER BY    LENGTH(L.DIR) DESC,    L.DOMAIN_LIMITED DESC,    L.SORT [[] ]
 

Пользователь 1313397

Посетитель

Сообщений: 70
Баллов: 7
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 07.08.2017

#19

0

24.05.2018 09:01:18

Цитата
Николай Свистов написал:

Цитата
Vladislav S.  написал:
Ошибка указывает на отсутствие соединения к БД и, в том числе, нету какой-то директории….проверяйте свой сервак

Сделал чек БД и ошибка сменилась на следующую

Код
 FILE: /home/bitrix/www/bitrix/modules/main/classes/mysql/main.php
 LINE:  99 
MySQL
 Query Error: SEL ECT L.*, L.LID  as  ID, L.LID  as  SITE_ID,    C.FORMAT_DATE,
 C.FORMAT_DATETIME, C.FORMAT_NAME, C.WEEK_START, C.CHARSET, C.DIRECTION 
FR OM b_lang L, b_culture C WHERE C.ID=L.CULTURE_ID  AND  L.ACTIVE= 'Y'  
ORDER BY    LENGTH(L.DIR) DESC,    L.DOMAIN_LIMITED DESC,    L.SORT [[] ]
 

Пробуйте перезалить базу данных, и сделайте проверку в битриксе, мне кажется там нужно будет исправить таблицы после проверки

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#20

0

24.05.2018 09:04:31

Цитата
Vladislav S. написал:

Цитата
Николай Свистов  написал:

Цитата
Vladislav S.  написал:
Ошибка указывает на отсутствие соединения к БД и, в том числе, нету какой-то директории….проверяйте свой сервак

Сделал чек БД и ошибка сменилась на следующую

Код
  FILE: /home/bitrix/www/bitrix/modules/main/classes/mysql/main.php
 LINE:   99  
MySQL
 Query Error: SEL ECT L.*, L.LID   as   ID, L.LID   as   SITE_ID,    C.FORMAT_DATE,
 C.FORMAT_DATETIME, C.FORMAT_NAME, C.WEEK_START, C.CHARSET, C.DIRECTION 
FR OM b_lang L, b_culture C WHERE C.ID=L.CULTURE_ID   AND   L.ACTIVE=  'Y'   
ORDER BY    LENGTH(L.DIR) DESC,    L.DOMAIN_LIMITED DESC,    L.SORT [[] ]
  

Пробуйте перезалить базу данных, и сделайте проверку в битриксе, мне кажется там нужно будет исправить таблицы после проверки

У меня битрикс не открывается. Могу перезалить средствами mysqldump, но не уверен что поможет

Прикрепленные файлы

86801e8bcd.jpg (105.9 КБ)

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#21

0

24.05.2018 09:07:20

Цитата
Vladislav S. написал:
мне кажется там нужно будет исправить таблицы после проверки

Сделал повторно mysqlcheck и всё прошло нормально. Все таблицы OK.

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#22

0

24.05.2018 10:34:15

Цитата
Vladislav S. написал:
Пробуйте перезалить базу данных

Перезалил — не помогло, всё та же ошибка

Код
FILE: /home/bitrix/www/bitrix/modules/main/classes/mysql/main.php
 LINE: 99
MySQL
 Query Error: SEL ECT L.*, L.LID as ID, L.LID as SITE_ID,    C.FORMAT_DATE,
 C.FORMAT_DATETIME, C.FORMAT_NAME, C.WEEK_START, C.CHARSET, C.DIRECTION 
FR OM b_lang L, b_culture C WHERE C.ID=L.CULTURE_ID AND L.ACTIVE='Y' 
ORDER BY    LENGTH(L.DIR) DESC,    L.DOMAIN_LIMITED DESC,    L.SORT [[] ]
 

Пользователь 136059

Гуру

Сообщений: 5418
Баллов: 636
Авторитет:

22

Рейтинг пользователя:

0

Регистрация: 16.07.2012

#23

0

24.05.2018 10:51:18

Цитата
Николай Свистов написал:
На 127.0.0.1 не подключается. Но в файлах конфигурации указано «localhost» , почему оно должно подключаться на 127.0.0.1 ?Я создал пользователя в ДБ  bxuser@127.0.0.1

Так в этом то и проблема: bxuser@127.0.0.1 и bxuser@localhost — это разные пользователи с точки зрения mysql.

Голосуй за идеи по развитию API Bitrix:
https://idea.1c-bitrix.ru/26707/
https://idea.1c-bitrix.ru/26709/
https://idea.1c-bitrix.ru/the-local-extension-folder-js/

 

Пользователь 1313397

Посетитель

Сообщений: 70
Баллов: 7
Авторитет:

1

Рейтинг пользователя:

0

Регистрация: 07.08.2017

#24

0

24.05.2018 11:38:10

 

Пользователь 1994877

Заглянувший

Сообщений: 10
Баллов: 1
Авторитет:

0

Рейтинг пользователя:

0

Регистрация: 07.05.2018

#25

0

24.05.2018 11:39:35

Совместно с

Vladislav S.

была найдена проблема.
В dbconn.php была лишняя строка define(«BX_USE_MYSQLI», true);

Обратите внимание: при редактировании файлов баз данных сторонними программами (Sublime Text, Notepad++ и др.) всегда учитывайте кодировку в которой открывается и сохраняется .sql файл базы данных. В случае допуска ошибки могут проявляться малопредсказуемые последствия работы сайта.

Duplicate entry ‘1’ for key ‘PRIMARY’

Требуется заменить во всей базе данных INSERT INTO на REPLACE INTO.

Multiple primary key defined

Убедитесь, что в базе в которую производится импорт нет каких-либо данных (база должна быть полностью очищена).

[BitrixMainDBSqlQueryException] Mysql query error: Illegal mix of collations for operation ‘UNION’ (400)

Проблема с разными кодировками таблиц (collation utf8_unicode_ci и utf8_general_ci).
Требуется заменить DEFAULT CHARSET=utf8 на DEFAULT CHARSET=utf8 COLLATE utf8_unicode_ci во всей базе данных.

MySQL Query Error: SELECT DISTINCT BE.ID as ID … which is not in SELECT list; this is incompatible with DISTINCT

Необходимо очистить содержимое папки /bitrix/tmp/

[BitrixMainDBConnectionException] Mysql connect error [localhost]: (1045) Access denied for user ‘***’@’localhost’ (using password: YES) (400)

Неверные данные для подключения к базе данных. Проверьте название базы данных, имя назначенного пользователя и его пароль в панели хостинга и отредактируйте данные в файлах /bitrix/php_interface/dbconn.php и /bitrix/.settings.php

Переменная sql_mode в MySQL должна быть пустая, текущее значение…

/bitrix/php_interface/after_connect_d7.php
добавить $connection->queryExecute(«SET sql_mode=»»);

/bitrix/php_interface/after_connect.php
добавить $DB->Query(«SET sql_mode=»»);

Ошибка innodb_strict_mode=ON, требуется OFF или Ошибка! Переменная sql_mode в MySQL должна быть пустая, текущее значение…

/bitrix/php_interface/after_connect.php
$DB->Query(«SET sql_mode=»»);
$DB->Query(«SET innodb_strict_mode=0»);

/bitrix/php_interface/after_connect_d7.php
$connection = BitrixMainApplication::getConnection();
$connection->queryExecute(«SET sql_mode=»»);
$connection->queryExecute(«SET innodb_strict_mode=0»);

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»;

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.

[[email protected]]# mysql -u root -psekret -h <IP_or_hostname> -P 3306

Code language: HTML, XML (xml)

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.

mysql> SELECT EXISTS(SELECT 1 FROM mysql.user WHERE user = 'username') Query OK, 0 rows affected (0.00 sec)

Code language: JavaScript (javascript)

If the user does not exist, you can create a new user:

mysql> CREATE USER 'username'@'localhost' IDENTIFIED BY 'password'; Query OK, 0 rows affected (0.00 sec)

Code language: JavaScript (javascript)

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:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;

Code language: JavaScript (javascript)

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:

mysql> SELECT Host, User FROM mysql.user WHERE User='user01'; +-------------+-------------+ | Host | User | +-------------+-------------+ | 192.168.0.1 | user01 | +-------------+-------------+ 1 row in set (0.00 sec)

Code language: JavaScript (javascript)

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.

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)

Code language: JavaScript (javascript)

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 :

mysql> set password for 'nonexistant'@'%' = 'helloworld'; Empty set (0.00 sec)

Code language: PHP (php)

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:

[[email protected]]# mysql -u user01 -p'hello$!*&^%$#@!' mysql: [Warning] Using a password on the command line interface can be insecure ... mysql>

Code language: PHP (php)

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.

  1. Stop the instance by running sudo systemctl stop mariadb
  2. Use mysqld_safe to start mysqld server by running the command: mysqld_ safe –user=mysql –skip-grant-tables –skip-networking
  3. Now you can open up a new terminal and access the MySQL server instance with root privileges by running mysql -u root -h localhost .
  4. 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;.
  5. Run SET PASSWORD FOR 'root'@'localhost' = '[email protected]!' to change the password for root user.
  6. 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’;
  7. Stop the mysqld_safe instance and restart MySQL again from systemctl.
  8. 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.

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.

Понравилась статья? Поделить с друзьями:
  • Mysql 2014 error
  • Mysql 1366 ошибка
  • Myrtille error 1001
  • Mypy ignore error
  • Myphoneexplorer obex errorcode d0 internal server error