This solution worked for me (http://dev.mysql.com/doc/refman/5.5/en/resetting-permissions.html) :
C.5.4.1.1. Resetting the Root Password: Windows Systems
On Windows, use the following procedure to reset the password for all MySQL root accounts:
Log on to your system as Administrator.
Stop the MySQL server if it is running. For a server that is running as a Windows service, go to the Services manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list and stop it.
If your server is not running as a service, you may need to use the Task Manager to force it to stop.
Create a text file containing the following statements. Replace the password with the password that you want to use.
UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
FLUSH PRIVILEGES;
Write the UPDATE and FLUSH statements each on a single line. The UPDATE statement resets the password for all root accounts, and the FLUSH statement tells the server to reload the grant tables into memory so that it notices the password change.
Save the file. For this example, the file will be named C:mysql-init.txt.
Open a console window to get to the command prompt: From the Start menu, select Run, then enter cmd as the command to be run.
Start the MySQL server with the special —init-file option (notice that the backslash in the option value is doubled):
C:> C:mysqlbinmysqld --init-file=C:\mysql-init.txt
If you installed MySQL to a location other than C:mysql, adjust the command accordingly.
The server executes the contents of the file named by the —init-file option at startup, changing each root account password.
You can also add the —console option to the command if you want server output to appear in the console window rather than in a log file.
If you installed MySQL using the MySQL Installation Wizard, you may need to specify a —defaults-file option:
C:> "C:Program FilesMySQLMySQL Server 5.5binmysqld.exe"
--defaults-file="C:\Program Files\MySQL\MySQL Server 5.5\my.ini"
--init-file=C:\mysql-init.txt
The appropriate —defaults-file setting can be found using the Services Manager: From the Start menu, select Control Panel, then Administrative Tools, then Services. Find the MySQL service in the list, right-click it, and choose the Properties option. The Path to executable field contains the —defaults-file setting.
After the server has started successfully, delete C:mysql-init.txt.
You should now be able to connect to the MySQL server as root using the new password. Stop the MySQL server, then restart it in normal mode again. If you run the server as a service, start it from the Windows Services window. If you start the server manually, use whatever command you normally use.
Страницы 1
Чтобы отправить ответ, вы должны войти или зарегистрироваться
1 2010-02-18 16:34:20
- mkostil
- Редкий гость
- Неактивен
- Зарегистрирован: 2010-02-18
- Сообщений: 5
Тема: Проблема при настройке mysql
При настройке, установив пароль, в окне processing configuration…, не выполняется пункт — Apply security settings. Я удалял мускл по-новому ставил, и так раз 5, потом решил попробовать как оно будет работать.
Запустил скрипт:
<?php
echo «php работает»;
$link=mysql_connect(«localhost»,»root»,»slagiotore»);
?>
Выдало:php работает
Warning: mysql_connect() [function.mysql-connect]: Access denied for user ‘root’@’localhost’ (using password: YES) in C:apachelocalhostwwwindex.php on line 11
При запуске phpmyadmin выдаёт вот такое:
Добро пожаловать в phpMyAdmin
Ошибка
Ответ MySQL: Документация
#1045 — Access denied for user ‘root’@’localhost’ (using password: YES)
phpMyAdmin не смог установить соединение с сервером MySQL. Проверьте хост, имя пользователя и пароль установленные в конфигурационном файле config.inc.php и удостоверьтесь, что они соответствуют данным полученным от администратора сервера MySQL.
Помогите пожалуйста новичку.
2 Ответ от Hanut 2010-02-18 17:17:52
- Hanut
- Модератор
- Неактивен
- Откуда: Рига, Латвия
- Зарегистрирован: 2006-07-02
- Сообщений: 9,726
Re: Проблема при настройке mysql
mkostil
Обычно выдает ошибку в пункте Apply security settings, если брандмауэр блокирует порт MySQL (3306).
Попробуйте установить MySQL отключившись от Интернет и выключив брандмауэр. Разумеется, в правилах брандмауэра надо разрешить процессу MySQL принятие соединений на порту 3306.
3 Ответ от mkostil 2010-02-20 02:57:39
- mkostil
- Редкий гость
- Неактивен
- Зарегистрирован: 2010-02-18
- Сообщений: 5
Re: Проблема при настройке mysql
Hanut
Пробовал отключаться от интернета, брандмауэр выключен, в исключениях добавил порт 3306, но результата нет. Подскажи пожалуйста ещё чего-нибудь, заранее спасибо
4 Ответ от Hanut 2010-02-20 11:57:33
- Hanut
- Модератор
- Неактивен
- Откуда: Рига, Латвия
- Зарегистрирован: 2006-07-02
- Сообщений: 9,726
Re: Проблема при настройке mysql
mkostil
Пробуйте запустить сервис MySQL из Control Panel -> Administrative Tools -> Services. Если не запустится, смотрите ошибки в журнале операционной системы или в журнале ошибок MySQL.
5 Ответ от mkostil 2010-02-20 12:57:26
- mkostil
- Редкий гость
- Неактивен
- Зарегистрирован: 2010-02-18
- Сообщений: 5
Re: Проблема при настройке mysql
Hanut
Дело в том что, служба мускл запускается и останавливается, не только с панели управления но и с помощью созданных ярлыков. Но при попытке подключения к БД, как я писал в первом сообщении, не получается.
6 Ответ от mkostil 2010-02-20 13:13:40
- mkostil
- Редкий гость
- Неактивен
- Зарегистрирован: 2010-02-18
- Сообщений: 5
Re: Проблема при настройке mysql
Hanut
При первой установке mysql, не исключаю, что мог натупить с паролями, читал что может самая первая БД не удаляться и из-за этого такая петрушка. Если это действительно так, то как мне её найти и удалить. Я удаляю мускл с панели управления + с програм файлс папку мускл.
7 Ответ от Hanut 2010-02-20 20:26:50
- Hanut
- Модератор
- Неактивен
- Откуда: Рига, Латвия
- Зарегистрирован: 2006-07-02
- Сообщений: 9,726
Re: Проблема при настройке mysql
Попробуйте зайти в MySQL из командной строки (cmd).
mysql -uroot -ppassword
Вместо password введите пароль пользователя root (ключ -p и последующий пароль должны быть вплотную, как написано).
Если захотите переустановить MySQL, то удалить надо так же каталог data, который находится здесь: C:Documents and SettingsAll UsersApplication DataMySQLMySQL Server 5.1data
8 Ответ от pau4ok 2010-02-21 15:06:55
- pau4ok
- Редкий гость
- Неактивен
- Откуда: г. Одесса
- Зарегистрирован: 2010-02-21
- Сообщений: 2
Re: Проблема при настройке mysql
У меня точно такая жа проблема, переустановил маскл но всеравно пишет, что не открыт порт. Возможно проблема в том что у меня роутер, но в его настройках я открыл порт 3306. Если через командную строку заходить то выбивает тот же эрор:
#1045 — Access denied for user ‘root’@’localhost’ (using password: YES)
9 Ответ от Hanut 2010-02-21 16:30:12
- Hanut
- Модератор
- Неактивен
- Откуда: Рига, Латвия
- Зарегистрирован: 2006-07-02
- Сообщений: 9,726
Re: Проблема при настройке mysql
pau4ok сказал:
#1045 — Access denied for user ‘root’@’localhost’ (using password: YES)
Это означает, что MySQL работает, но пароль не принимается.
10 Ответ от pau4ok 2010-02-21 16:35:43
- pau4ok
- Редкий гость
- Неактивен
- Откуда: г. Одесса
- Зарегистрирован: 2010-02-21
- Сообщений: 2
Re: Проблема при настройке mysql
Ммм и что делать?)
11 Ответ от Hanut 2010-02-21 17:20:06
- Hanut
- Модератор
- Неактивен
- Откуда: Рига, Латвия
- Зарегистрирован: 2006-07-02
- Сообщений: 9,726
Re: Проблема при настройке mysql
pau4ok
Попробуйте переустановить MySQL удалив сперва каталог data.
12 Ответ от mkostil 2010-02-21 17:28:10
- mkostil
- Редкий гость
- Неактивен
- Зарегистрирован: 2010-02-18
- Сообщений: 5
Re: Проблема при настройке mysql
Hanut
ОГРОМНЕЙШЕЕ СПАСИБО!!!!!!!!!!!!!!!
Переустановил я мускл, а перед этим удалил каталог, правда не data а MySql в которой находиться data, я думаю разницы нет, и все прошло как по маслу. Только если кто-то столкнётся с этой проблемой, перегрузите комп, а то я сразу обрадовался конфигурация прошла успешно, а не тестовый скрипт не хотел работать, на phpmyadmin зашёл за 3 разом, а после перезагрузки всё работает. Hanut ещё раз тебе спасибо.
13 Ответ от Skolzkiy 2011-04-11 19:45:44
- Skolzkiy
- Редкий гость
- Неактивен
- Зарегистрирован: 2011-04-11
- Сообщений: 3
Re: Проблема при настройке mysql
Народ..выручайте)
У меня тоже возникает проблема на этом месте….но с другой ошибкой
The securite setting could not be applied to the database the conection has faild with the following error.
Error Nr. 2003
Can’t connect to MySQL server on ‘localhost'(10061)
И там ещё много чего…)
Кто может сказать в чём проблема..я уже переустанавливал программу 10 раз…перезагружал, порт открывал…но толку 0…а вот как указано с папкой data, дак её я не нашёл вообще….искал в корне где установлена программа, но там были только….bin, lib, share….и ещё разные файлы…версия программы 5.1ююю
Заранее спасибки;)
14 Ответ от DiapaZon 2011-04-11 20:36:04
- DiapaZon
- Редкий гость
- Неактивен
- Зарегистрирован: 2011-04-11
- Сообщений: 2
Re: Проблема при настройке mysql
Подскажите пожалуйста как мне изменить сохранения БД из C:Documents and SettingsAll UsersApplication DataMySQL Server 5.1data в CMySQL5data Заранее спасибо)
15 Ответ от Hanut 2011-04-11 21:59:36
- Hanut
- Модератор
- Неактивен
- Откуда: Рига, Латвия
- Зарегистрирован: 2006-07-02
- Сообщений: 9,726
Re: Проблема при настройке mysql
Skolzkiy сказал:
с папкой data, дак её я не нашёл вообще
Ищите где-то здесь.
C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.5/Data/
16 Ответ от Hanut 2011-04-11 22:00:46
- Hanut
- Модератор
- Неактивен
- Откуда: Рига, Латвия
- Зарегистрирован: 2006-07-02
- Сообщений: 9,726
Re: Проблема при настройке mysql
DiapaZon сказал:
Подскажите пожалуйста как мне изменить сохранения БД из C:Documents and SettingsAll UsersApplication DataMySQL Server 5.1data в CMySQL5data Заранее спасибо)
В my.ini директива datadir.
17 Ответ от Skolzkiy 2011-04-11 22:12:27
- Skolzkiy
- Редкий гость
- Неактивен
- Зарегистрирован: 2011-04-11
- Сообщений: 3
Re: Проблема при настройке mysql
Hanut сказал:
Ищите где-то здесь.
C:/Documents and Settings/All Users/Application Data/MySQL/MySQL Server 5.5/Data/
В том то и дело..я при установки путь не менял..и он по стандарту в C фигачил…установил 66 версию..папка дата появляется….но удаляю её..но толку от этого 0…(
ставлю заново мускл..но всё равно ошибку выдаёт…и я так понимаю, ругается он на порт((((
А да…и по чему то, после удаления… остается название серва…т.е. нельзя его больше создать…так как он уже существует…..я хз вообще чё делать…(
18 Ответ от Hanut 2011-04-11 23:31:34
- Hanut
- Модератор
- Неактивен
- Откуда: Рига, Латвия
- Зарегистрирован: 2006-07-02
- Сообщений: 9,726
Re: Проблема при настройке mysql
Skolzkiy сказал:
и по чему то, после удаления… остается название серва
Это я не понял. Где остается? Если остается сервис MySQL, значит вы его не удалили.
19 Ответ от DmitryV 2011-04-12 10:45:13
- DmitryV
- Пенсионер
- Неактивен
- Откуда: Санкт-Петербург, Россия
- Зарегистрирован: 2010-07-31
- Сообщений: 558
Re: Проблема при настройке mysql
MySQL версию выше 5.5 не устанавливайте 6 это сырые беты.
20 Ответ от Skolzkiy 2011-04-12 10:52:15
- Skolzkiy
- Редкий гость
- Неактивен
- Зарегистрирован: 2011-04-11
- Сообщений: 3
Re: Проблема при настройке mysql
Hanut сказал:
Это я не понял. Где остается? Если остается сервис MySQL, значит вы его не удалили.
Ну при настройках там есть название типа сервиса…ну вот там и остаётся по чему то…хотя через панель программа ыла удалена…
DmitryV сказал:
MySQL версию выше 5.5 не устанавливайте 6 это сырые беты.
Спасибки…буду знать)
Страницы 1
Чтобы отправить ответ, вы должны войти или зарегистрироваться
This might seem redundant but I was unable to find a correct solution.
I was unable to login to mysql using the mysql console.It is asking for a password and I have no clue what I actually entered.(Is there a way to get the password or change it?)
This is how my config.inc look.
When I try to open phpmyadmin I get this error(#1045 — Access denied for user ‘root’@’localhost’ (using password: YES))
<?php
/* Servers configuration */
$i = 0;
/* Server: localhost [1] */
$i++;
$cfg['Servers'][$i]['verbose'] = 'localhost';
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['port'] = '3306';
$cfg['Servers'][$i]['socket'] = '';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$cfg['Servers'][$i]['user'] = 'root';
$cfg['Servers'][$i]['password'] = 'prakash123';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
/* End of servers configuration */
$cfg['DefaultLang'] = 'en-utf-8';
$cfg['ServerDefault'] = 1;
$cfg['UploadDir'] = '';
$cfg['SaveDir'] = '';
/* rajk - for blobstreaming */
$cfg['Servers'][$i]['bs_garbage_threshold'] = 50;
$cfg['Servers'][$i]['bs_repository_threshold'] = '32M';
$cfg['Servers'][$i]['bs_temp_blob_timeout'] = 600;
$cfg['Servers'][$i]['bs_temp_log_threshold'] = '32M';
?>
I have tried to uninstall( Plus Deleted all the related files) WAMP and reinstall.It didn’t help either.
While reinstalling WAMP server it is not asking for any username password stuff I don’t know why.
Any help is highly appreciated.
asked May 30, 2013 at 20:54
4
I first changed the root password running mysql at a prompt with
mysql -u root -p
Update password:
UPDATE mysql.user SET Password=PASSWORD('MyNewPass') WHERE User='root';
Edited line in the file config.inc.php
with the new root password:
$cfg['Servers'][$i]['password'] = 'MyNewPass'
Stop and re-start mysql service (in Windows: mysql_stop.bat
/mysql_start.bat
)
and got phpMyAdmin to work!
EDIT 2017: for MySQL≥5.7 use authentication_string
in place of Password
(see this answer):
`UPDATE mysql.user SET authentication_string=PASSWORD('MyNewPass') WHERE User='root';
`
Ritesh
4,6346 gold badges27 silver badges40 bronze badges
answered Oct 15, 2013 at 11:16
user2314737user2314737
26.6k18 gold badges102 silver badges113 bronze badges
3
The problem was I have 2 instances of Mysql installed and I didn’t know the password for both instances.Just check if port 80 is used by any of the programs.
This is what I did
1.Quit Skype because it was using port 80.(Please check if port 80 is used by any other program).
2.Search for Mysql services in task manager and stop it.
3.Now delete all the related mysql files.Make sure you delete all the files.
4.Reinstall
radbyx
9,27221 gold badges84 silver badges127 bronze badges
answered Aug 8, 2013 at 20:19
PrakashPrakash
7,7364 gold badges47 silver badges44 bronze badges
Well, there are many solutions already given above. If there are none of them works, maybe you should just try to reset your password again to ‘root’ as described here, and then reopen http://localhost/phpMyAdmin/
in other browser. At least this solution works for me.
answered Oct 27, 2013 at 20:18
yunhasnawayunhasnawa
8151 gold badge14 silver badges30 bronze badges
This worked for me.
In your config file
$cfg['Servers']['$i']['password'] = 'yourpassword';
In your mysql shell, login as root
mysql -u root
change your password or update if you’ve forgotten the old one
UPDATE mysql.user SET Password=PASSWORD('yourpassword') WHERE User='root';
stop and restart your mysql server from the xampp control panel. phpmyadmin can login to see your databases
answered Jul 1, 2018 at 23:43
mysql.exe->Run as administrator or go to following path C:wampbinmysqlmysql5.5.24bin and than right click on mysql.exe go to properties and than select tab as Compatibility and see the bottom of dialog box in privilege level and just check the Run this program as an administrator and then click apply ok.finished now you open success phpMyadmin. bye
answered Aug 5, 2013 at 15:40
mysql -u root -p
UPDATE mysql.user SET Password=PASSWORD('mypass') WHERE User='root';
- Flush the privileges:
FLUSH PRIVILEGES;
- Exit by typing:
Exit
-
Edited line in the file config.inc.php with the new root password:
$cfg['Servers'][$i]['password'] = 'mypass'
-
be succss
answered Dec 29, 2014 at 9:08
1
Go to ‘config.inc.php’. Write your password over here — $cfg['Servers'][$i]['password'] =''
answered Jan 21, 2015 at 17:42
halkujabrahalkujabra
2,8443 gold badges25 silver badges35 bronze badges
This process is quite simple in correcting the the error. What is happening is a failure to connect to phpMyAdmin. In order to fix the problem you simply need to provide the correct password to the system phpMyAdmin configuration file located in appsphpMyadminconfig.ini.php
1. the root should already be set as user
2. Insert the password between ‘ ‘ and that it.
If you still have problems then this means that the user name and /or the password need to be updated or inserted into the DB. to do this use the command line tool and do an update.
UPDATE mysql.user SET Password=PASSWORD(‘Johnny59 or whatever you want to use’) WHERE User=’root’;
answered Jan 26, 2015 at 2:52
Go to config.inc.php
, find $cfg['Servers'][$i]['password']
and remove any password provided, i.e change $cfg['Servers'][$i]['password'] = 'password';
with $cfg['Servers'][$i]['password'] = '';
Now you can launch phpMyAdmin
Selecting Users menu from phpMyAdmin, select the root user and click Edit previlidges.
Now scroll down to Change Password area, switch between No Password and Password to provide your new password.
that’s it.
answered Jun 20, 2015 at 8:52
I had the same error today. I had installed Djangostack and when I checked my task manager there were two instances of mysqld running. I checked one was for wamp server and the other was for django stack. I ended the one for django stack, restarted all services in wamp server and I was able to access phpmyadmin
answered Jun 22, 2015 at 9:15
NgenoNgeno
213 bronze badges
after installation i started wamp and i was asked for user and pass which were already set on default (user:admin pass: dots), and that was wrong with a message from your topic. Than, i just entered:
Username: root Password: (leave it empty)
and it worked for me!!
answered Aug 2, 2016 at 11:39
0
-
Go to
C:xamppphpMyAdmin
-
Edit the
config.inc.php
file -
Replace
$cfg['Servers'][$i]['auth_type'] = 'config';
by
$cfg['Servers'][$i]['auth_type'] = 'cookie';
For now on the PHPMyAdmin
will ask you for your password, no more error.
ata
3,3205 gold badges20 silver badges31 bronze badges
answered Feb 20, 2018 at 20:35
Try the following code:
$cfg['Servers'][$i]['password'] = '';
if you see Password column field as ‘No’ for the ‘root’ user in Users Overview
page of phpMyAdmin.
рüффп
5,13534 gold badges67 silver badges113 bronze badges
answered Oct 24, 2013 at 9:17
PerisPeris
293 bronze badges
with MariaDb, above solutions doesn’t works.
Use (exemple below with ubuntu 16.04 and mariadb-server Distrib 10.0.28):
sudo mysql_secure_installation
…
Change the root password? [Y/n]
New password:
answered Jan 26, 2017 at 10:45
bcag2bcag2
1,9081 gold badge15 silver badges31 bronze badges
I have encountered similar mistakes, and later found that my password is wrong.
answered Aug 14, 2017 at 1:28
管浩浩管浩浩
631 silver badge4 bronze badges
For UNIX, try this. It worked for me:
- connect MySQL use Navicat Premium with inital root/»password»
UPDATE mysql.user
SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
WHERE User = 'root' AND Host = 'localhost';
FLUSH PRIVILEGES;- restart MySQL
answered Feb 17, 2017 at 2:37
AaronAaron
191 bronze badge
1
First you have to go config.inc.php file then change the following instruction
$cfg['Servers'][$i]['user'] ='';
$cfg['Servers'][$i]['password'] ='';
or
answered Aug 23, 2017 at 15:30
1
If you arrived here because you can’t log into your phpMyAdmin, then try the root password from your Mysql instead of the password you put during phpMyAdmin installation.
answered Oct 10, 2017 at 11:38
Kaizoku GambareKaizoku Gambare
3,0533 gold badges29 silver badges41 bronze badges
Just now I have this situation and I have tried this way which is very easy.
First stop your mysql service using this command:
service mysql stop
and then just again start your mysql service using this command
service mysql start
I hope it may help others…
STiLeTT
1,02310 silver badges23 bronze badges
answered Dec 1, 2017 at 10:51
Sachin ShahSachin Shah
4,4543 gold badges23 silver badges50 bronze badges
After I updated my MySql, I was getting the same error message.
It turned out that after installing a different version on MySql, inside the my.ini, the port was different. Previous MySql version had port 3306 but the new one have port 3308.
Check your MySql my.ini, if it is different use the port from .ini in your connection.
answered Jan 9, 2020 at 23:52
GuntarGuntar
4598 silver badges23 bronze badges
php artisan serve
this command get the env contents for the first time and if you update .env file need to restart it.
in my case my username and dbname is valid and php artisan migrate worked
but need to cntrl+c , to cancel php artisan serve , and run it again
php artisan serve
answered Feb 19, 2020 at 17:51
Check the name of Environment Variable
Case with me:
- I was using
sqlalchemy
in apython-flask
project and got this issue. - IDE used: PyCharm
- In my
config.py
file I had setupSQLALCHEMY_DATABASE_URI
as:
SQLALCHEMY_DATABASE_URI = os.getenv("DATABASE_URI")
Mistake I did (it was a silly mistake 😅)
- While setting
evironment_variables
in PyCharm, I did:
SQLALCHEMY_DATABASE_URI=<my_db_uri>
Solution
- I changed the above to:
DATABASE_URI=<my_db_uri>
Namaste 🙏
answered Apr 6, 2021 at 6:34
Deepam GuptaDeepam Gupta
2,2581 gold badge28 silver badges33 bronze badges
In the my.ini file in C:xamppmysqlbin, add the following line after the [mysqld]
command under #Mysql Server
:
skip-grant-tables
This should remove the error 1045.
answered Dec 20, 2017 at 7:23
1
if multiple myslq running on same port no
enter image description here
Right click on wamp and test port 3306
if its wampmysqld64 its correct else change port no and restart server
radbyx
9,27221 gold badges84 silver badges127 bronze badges
answered Jun 16, 2018 at 12:00
SachinsSachins
311 silver badge7 bronze badges
When loading mysql, it always goes wrong when it is finally started. The error content is as follows:
Is the final Apply security setting
prompt:
The security settings could not be applied to the database because the connection has failed with the following error.
Error Nr. 1045
Access denied for user ‘root’@’localhost’ (using password: YES)
If a personal firewall is running on your machine, please make sure you have opened the TCP port 3306 for connections. Otherwise no client application can connect to the server. After you have opened the port please press [Retry] to apply the security settings.
If you are re-installing after you just uninstalled the MySQL server please note that the data directory was not removed automatically. Therefore the old password from your last installation is still needed to connect to the server. In this case please select skip now and re-run the Configuration Wizard from the start menu.
Solution:
1, uninstall MySQL
2, delete the directory C: / Documents and Settings / All Users / Application Data / MySQL
3, re-install MySQL just fine
How are you C:There is no Application Data folder under /Documents and Settings/All Users, select: Tools — Folder Options — View — Select to display all files and folders
Mysql database uninstall is not complete, configuration error solution
The security settings could not be applied to the database because the connection has failed with the following error.
Error Nr. 2003
Can’t connect to MySQL server on ‘localhost’ (10061)
If a personal firewall is running on your machine, please make sure you have opened the TCP port 3306 for connections. Otherwise no client application can connect to the server. After you have opened the port please press [Retry] to apply the security settings.
If you are re-installing after you just uninstalled the MySQL server please note that the data directory was not removed automatically. Therefore the old password from your last installation is still needed to connect to the server. In this case please select skip now and re-run the Configuration Wizard from the start menu.
*****************************************************************************************
The security settings could not be applied to the database because the connection has failed with the following error.
Error Nr. 1045
Access denied for user ‘root’@’localhost’ (using password: YES)
If a personal firewall is running on your machine, please make sure you have opened the TCP port 3306 for connections. Otherwise no client application can connect to the server. After you have opened the port please press [Retry] to apply the security settings.
If you are re-installing after you just uninstalled the MySQL server please note that the data directory was not removed automatically. Therefore the old password from your last installation is still needed to connect to the server. In this case please select skip now and re-run the Configuration Wizard from the start menu.
Solution for apply security setting error during MySQL 5.1 installation
1, uninstall MySQL
2, delete the directory C: / Documents and Settings / All Users / Application Data / MySQL
3, re-install MySQL, OK.
——————————————
[MySQL] Could not start the service MySQL solution
Install mysql 5.1.33, the third Start Service in the Execute configurattion step when running the Server Instance Configuration wizard goes wrong, the error message is Could not start the service MySQL (this is usually because mysql is installed, uninstall is not Clean caused. After uninstalling and restarting and then reinstalling. Pay attention to the service, if you can not uninstall, you can use mysqld-nt-remove to uninstall).
The specific method is as follows:
Check if there is mysql in the service, if there is any service to stop it;
Run Add and Remove Programs in the Control Panel to uninstall mysql.
Open the registry after uninstalling, check the key value under HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services, if there is related mysql key value (mysql, mysqladmin), delete it;
Restart, delete the mysql installation residual directory (view the service, there is no mysql in the service);
Reinstall mysql. Do not run the Server Instance Configuration wizard after installation. After restarting, run the wizard in the Start menu.
PS: A method worthy of reference
———————————————
Msyql install to the last step start service error solution
1, to the control panel first delete mysql.
2. Go to the c:C:/Program Files directory and delete the mysql directory.
3. If there are still setting directories in other disks, delete them. Empty directories should also be deleted.
4. Go to regedit to put the registry
HKEY_LOCAL_MACHINE/SYSTEM/ControlSet001/Services/Eventlog/Applications/MySQL
HKEY_LOCAL_MACHINE/SYSTEM/ControlSet002/Services/Eventlog/Applications/MySQL
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services/Eventlog/Applications/MySQL
If you have any, delete it all!
(Tips: Find «mysql» with F3 loop)
5. If the mysql content in the task manager is also deleted
6, shut down the firewall
7, reinstall mysql (I did not restart the computer here)
When reloading it is necessary, restart the computer, disable IIS, and delete temporary files in temp.
If it is not possible, when configuring mysql, change the mysql service to a service name.
******************************************************************************************
—————————
An error occurred while deleting the item.
—————————
Unable to delete LEGACY_MYSQL51: An error occurred while deleting the item.
—————————
Determine
—————————
Solution: right click in the registry key to increase all permissions of administrators
После первой установки и настройки MySQL на Windows Vista, не удалось подключится к базе и зайти с установленным паролем. Принял решение переустановить MySQL. После переустановки оказалось что где то еще остались не удаленные части MySQL. Вовремя применения параметров безопасности получил следующую ошибку:
The security settings could not be applied to the database because the connection has failed with the following error. Error Nr. 1045 Access denied for user ‘root’@’localhost’ (using password: YES) If a personal firewall is running on your machine, please make sure you have opened the TCP port 3306 for connections. Otherwise no client application can connect to the server. After you have opened the port please press [Retry] to apply the security settings. If you are re-installing after you just uninstalled the MySQL server please note that the data directory was not removed automatically. Therefore the old password from your last installation is still needed to connect to the server. In this case please select skip now and re-run the Configuration Wizard from the start menu.
Поискав в файле конфигурации my.ini (находится в папке установки MySQL) нашел следующие строки:
#Path to the database root
datadir=»C:/ProgramData/MySQL/MySQL Server 5.1/Data/»
Оказалось что данная папка чистится не полностью, и данные о пользователи остаются после удаления MySQL. После удаления папки и очередной переустановки MySQL. Мастер настройки больше не предлагал сменить старый пароль, а предложил установить новый.
During our work in support, we see this again and again: “I try to connect to MySQL and am getting a 1045 error”, and most times it comes accompanied with “…but I am sure my user and password are OK”. So we decided it was worth showing other reasons this error may occur.
MySQL 1045 error Access Denied triggers in the following cases:
1) Connecting to wrong host:
[engineer@percona]# mysql -u root -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) |
If not specifying the host to connect (with -h flag), MySQL client will try to connect to the localhost instance while you may be trying to connect to another host/port instance.
Fix: Double check if you are trying to connect to localhost, or be sure to specify host and port if it’s not localhost:
[engineer@percona]# mysql -u root -psekret -h <IP> -P 3306 |
2) User does not exist:
[engineer@percona]# mysql -u nonexistant -psekret -h localhost mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Double check if the user exists:
mysql> SELECT User FROM mysql.user WHERE User=‘nonexistant’; Empty set (0.00 sec) |
If the user does not exist, create a new user:
mysql> CREATE USER ‘nonexistant’@‘localhost’ IDENTIFIED BY ‘sekret’; Query OK, 0 rows affected (0.00 sec) |
3) User exists but client host does not have permission to connect:
[engineer@percona]# mysql -u nonexistant -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: 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=‘nonexistant’; +————-+————-+ | Host | User | +————-+————-+ | 192.168.0.1 | nonexistant | +————-+————-+ 1 row in set (0.00 sec) |
If you need to check from which IP the client is connecting, you can use the following Linux commands for server IP:
[engineer@percona]# ip address | grep inet | grep -v inet6 inet 127.0.0.1/8 scope host lo inet 192.168.0.20/24 brd 192.168.0.255 scope global dynamic wlp58s0 |
or for public IP:
[engineer@percona]# dig +short myip.opendns.com @resolver1.opendns.com 177.128.214.181 |
You can then create a user with correct Host (client IP), or with ‘%’ (wildcard) to match any possible IP:
mysql> CREATE USER ‘nonexistant’@‘%’ IDENTIFIED BY ‘sekret’; Query OK, 0 rows affected (0.00 sec) |
4) Password is wrong, or the user forgot his password:
[engineer@percona]# mysql -u nonexistant -pforgotten mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Check and/or reset password:
You cannot read user passwords in plain text from MySQL as the password hash is used for authentication, but you can compare hash strings with “PASSWORD” function:
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) |
We can see that PASSWORD(‘forgotten’) hash does not match the authentication_string column, which means password string=’forgotten’ is not the correct password to log in. Also, in case the user has multiple hosts (with different password), he may be trying to connect using the password for the wrong host.
In case you need to override the password you can execute the following query:
mysql> set password for ‘nonexistant’@‘%’ = ‘hello$!world’; Empty set (0.00 sec) |
5) Special characters in the password being converted by Bash:
[engineer@percona]# mysql -u nonexistant -phello$!world mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘nonexistant’@‘localhost’ (using password: YES) |
Fix: Prevent bash from interpreting special characters by wrapping password in single quotes:
[engineer@percona]# mysql -u nonexistant -p’hello$!world’ mysql: [Warning] Using a password on the command line interface can be insecure ... mysql> |
6) SSL is required but the client is not using it:
mysql> create user ‘ssluser’@‘%’ identified by ‘sekret’; Query OK, 0 rows affected (0.00 sec) mysql> alter user ‘ssluser’@‘%’ require ssl; Query OK, 0 rows affected (0.00 sec) ... [engineer@percona]# mysql -u ssluser -psekret mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘ssluser’@‘localhost’ (using password: YES) |
Fix: Adding –ssl-mode flag (–ssl flag is deprecated but can be used too)
[engineer@percona]# mysql -u ssluser -psekret —ssl-mode=REQUIRED ... mysql> |
You can read more in-depth on how to configure SSL in MySQL in the blog post about “Setting up MySQL SSL and Secure Connections” and “SSL in 5.6 and 5.7“.
7) PAM backend not working:
mysql> CREATE USER ‘ap_user’@‘%’ IDENTIFIED WITH auth_pam; Query OK, 0 rows affected (0.00 sec) ... [engineer@percona]# mysql -u ap_user -pap_user_pass mysql: [Warning] Using a password on the command line interface can be insecure. ERROR 1045 (28000): Access denied for user ‘ap_user’@‘localhost’ (using password: YES) |
Fix: Double check user/password is correct for the user to authenticate with the PAM currently being used.
In my example, I am using Linux shadow files for authentication. In order to check if the user exists:
[engineer@percona]# cat /etc/passwd | grep ap_user ap_user:x:1000:1000::/home/ap_user:/bin/bash |
To reset password:
[engineer@percona]# sudo passwd ap_user Changing password for user ap_user. New password: |
Finally, if you are genuinely locked out and need to circumvent the authentication mechanisms in order to regain access to the database, here are a few simple steps to do so:
- Stop the instance
- Edit my.cnf and add skip-grant-tables under [mysqld] (this will allow access to MySQL without prompting for a password). On MySQL 8.0, skip-networking is automatically enabled (only allows access to MySQL from localhost), but for previous MySQL versions it’s suggested to also add –skip-networking under [mysqld]
- Start the instance
- Access with root user (mysql -uroot -hlocalhost);
-
Issue the necessary GRANT/CREATE USER/SET PASSWORD to correct the issue (likely setting a known root password will be the right thing: SET PASSWORD FOR ‘root’@’localhost’ = ‘S0vrySekr3t’). Using grant-skip-tables won’t read grants into memory and GRANT/CREATE/SET PASSWORD statements won’t work straight away. First, you need to execute “FLUSH PRIVILEGES;” before executing any GRANT/CREATE/SET PASSWORD statement, or 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 instance
- Edit my.cnf and remove skip-grant-tables and skip-networking
- Start MySQL again
- You should be able to login with root from the localhost and do any other necessary corrective operations with root user.
Learn more about Percona Server for MySQL
Дата: 25.11.2013
Автор: Василий Лукьянчиков , vl (at) sqlinfo (dot) ru
Статистика форума SQLinfo показывает, что одной из наиболее популярных проблем является ошибка mysql №1045 (ошибка доступа).
Текст ошибки содержит имя пользователя, которому отказано в доступе, компьютер, с которого производилось подключение, а также ключевое слово YES или NO, которые показывают использовался ли при этом пароль или была попытка выполнить подключение с пустым паролем.
Типичные примеры:
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES) — сервер MySQL
— сообщает, что была неудачная попытка подключения с локальной машины пользователя с именем root и
— не пустым паролем.
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: NO) — отказано в
— доступе с локальной машины пользователю с именем root при попытке подключения с пустым паролем.
ERROR 1045 (28000): Access denied for user ‘ODBC’@‘localhost’ (using password: NO) — отказано в
— доступе с локальной машины пользователю с именем ODBC при попытке подключения с пустым паролем.
Причина возникновения ошибки 1045
Как ни банально, но единственная причина это неправильная комбинация пользователя и пароля. Обратите внимание, речь идет о комбинации пользователь и пароль, а не имя пользователя и пароль. Это очень важный момент, так как в MySQL пользователь характеризуется двумя параметрами: именем и хостом, с которого он может обращаться. Синтаксически записывается как ‘имя пользователя’@’имя хоста’.
Таким образом, причина возникновения MySQL error 1045 — неправильная комбинация трех параметров: имени пользователя, хоста и пароля.
В качестве имени хоста могут выступать ip адреса, доменные имена, ключевые слова (например, localhost для обозначения локальной машины) и групповые символы (например, % для обозначения любого компьютера кроме локального). Подробный синтаксис смотрите в документации
Замечание: Важно понимать, что в базе не существует просто пользователя с заданным именем (например, root), а существует или пользователь с именем root, имеющий право подключаться с заданного хоста (например, root@localhost) или даже несколько разных пользователей с именем root (root@127.0.0.1, root@webew.ru, root@’мой домашний ip’ и т.д.) каждый со своим паролем и правами.
Примеры.
1) Если вы не указали в явном виде имя хоста
GRANT ALL ON publications.* TO ‘ODBC’ IDENTIFIED BY ‘newpass’;
то у вас будет создан пользователь ‘ODBC’@’%’ и при попытке подключения с локальной машины вы получите ошибку:
ERROR 1045 (28000): Access denied for user ‘ODBC’@‘localhost’ (using password: YES)
так как пользователя ‘ODBC’@’localhost’ у вас не существует.
2) Другой первопричиной ошибки mysql 1045 может быть неправильное использование кавычек.
CREATE USER ‘new_user@localhost’ IDENTIFIED BY ‘mypass’; — будет создан пользователь ‘new_user@localhost’@’%’
Правильно имя пользователя и хоста нужно заключать в кавычки отдельно, т.е. ‘имя пользователя’@’имя хоста’
3) Неочевидный вариант. IP адрес 127.0.0.1 в имени хоста соответствует ключевому слову localhost. С одной стороны, root@localhost и ‘root’@’127.0.0.1’ это синонимы, с другой, можно создать двух пользователей с разными паролями. И при подключении будет выбран тот, который распологается в таблице привелегий (mysql.user) раньше.
4) Аккаунт с пустым именем пользователя трактуется сервером MySQL как анонимный, т.е. позволяет подключаться пользователю с произвольным именем или без указания имени.
Например, вы создали пользователя »@localhost с пустым паролем, чтобы каждый мог подключиться к базе. Однако, если при подключении вы укажите пароль отличный от пустого, то получите ошибку 1045. Как говорилось ранее, нужно совпадение трех параметров: имени пользователя, хоста и пароля, а пароль в данном случае не совпадает с тем, что в базе.
Что делать?
Во-первых, нужно убедиться, что вы используете правильные имя пользователя и пароль. Для этого нужно подключиться к MySQL с правами администратора (если ошибка 1045 не дает такой возможности, то нужно перезапустить сервер MySQL в режиме —skip-grant-tables), посмотреть содержимое таблицы user служебной базы mysql, в которой хранится информация о пользователях, и при необходимости отредактировать её.
Пример.
SELECT user,host,password FROM mysql.user;
+—————+——————+——————————————-+
| user | host | password |
+—————+——————+——————————————-+
| root | house-f26710394 | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
| aa | localhost | *196BDEDE2AE4F84CA44C47D54D78478C7E2BD7B7 |
| test | localhost | |
| new_user | % | |
| | % | *D7D6F58029EDE62070BA204436DE23AC54D8BD8A |
| new@localhost | % | *ADD102DFD6933E93BCAD95E311360EC45494AA6E |
| root | localhost | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
+—————+——————+——————————————-+
Если изначально была ошибка:
-
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES)
значит вы указывали при подключении неверный пароль, так как пользователь root@localhost существует. Сам пароль храниться в зашифрованном виде и его нельзя узнать, можно лишь задать новый
SET PASSWORD FOR root@localhost=PASSWORD(‘новый пароль’);
-
ERROR 1045 (28000): Access denied for user ‘ODBC’@‘localhost’ (using password: YES)
в данном случае в таблице привилегий отсутствует пользователь ‘ODBC’@’localhost’. Его нужно создать, используя команды GRANT, CREATE USER и SET PASSWORD.
Экзотический пример. Устанавливаете новый пароль для root@localhost в режиме —skip-grant-tables, однако после перезагрузки сервера по прежнему возникает ошибка при подключении через консольный клиент:
ERROR 1045 (28000): Access denied for user ‘root’@‘localhost’ (using password: YES)
Оказалось, что было установлено два сервера MySQL, настроенных на один порт.
phpmyadmin
При открытии в браузере phpmyadmin получаете сообщение:
Error
MySQL said:
#1045 — Access denied for user ‘root’@’localhost’ (using password: NO)
Connection for controluser as defined in your configuration failed.
phpMyAdmin tried to connect to the MySQL server, and the server rejected the connection. You should check the host, username and password in your configuration and make sure that they correspond to the information given by the administrator of the MySQL server.
Ни логина, ни пароля вы не вводили, да и пхпадмин их нигде требовал, сразу выдавая сообщение об ошибке. Причина в том, что данные для авторизации берутся из конфигурационного файла config.inc.php Необходимо заменить в нем строчки
$cfg[‘Servers’][$i][‘user’] = ‘root’; // MySQL user
$cfg[‘Servers’][$i][‘password’] = »; // MySQL password (only needed
на
$cfg[‘Servers’][$i][‘user’] = ‘ЛОГИН’;
$cfg[‘Servers’][$i][‘password’] = ‘ПАРОЛЬ’
Установка новой версии
Устанавливаете новую версию MySQL, но в конце при завершении конфигурации выпадает ошибка:
ERROR Nr. 1045
Access denied for user ‘root’@‘localhost’ (using password: NO)
Это происходит потому, что ранее у вас стоял MySQL, который вы удалили без сноса самих баз. Если вы не помните старый пароль и вам нужны эти данные, то выполните установку новой версии без смены пароля, а потом смените пароль вручную через режим —skip-grant-tables.
P.S. Статья написана по материалам форума SQLinfo, т.е. в ней описаны не все потенциально возможные случаи возникновения ошибки mysql №1045, а только те, что обсуждались на форуме. Если ваш случай не рассмотрен в статье, то задавайте вопрос на форуме SQLinfo
Вам ответят, а статья будет расширена.
Дата публикации: 25.11.2013
© Все права на данную статью принадлежат порталу SQLInfo.ru. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.