Дата: 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. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.
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,6546 gold badges27 silver badges40 bronze badges
answered Oct 15, 2013 at 11:16
user2314737user2314737
26.7k18 gold badges102 silver badges114 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,31221 gold badges84 silver badges127 bronze badges
answered Aug 8, 2013 at 20:19
PrakashPrakash
7,7564 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,15334 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,9381 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,0833 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,3081 gold badge29 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,31221 gold badges84 silver badges127 bronze badges
answered Jun 16, 2018 at 12:00
SachinsSachins
311 silver badge7 bronze badges
Note: For MySQL 5.7+, please see the answer from Lahiru to this question. That contains more current information.
For MySQL < 5.7:
The default root password is blank (i.e., an empty string), not root
. So you can just log in as:
mysql -u root
You should obviously change your root password after installation:
mysqladmin -u root password [newpassword]
In most cases you should also set up individual user accounts before working extensively with the database as well.
answered Feb 21, 2014 at 20:54
Mike BrantMike Brant
70.4k10 gold badges98 silver badges103 bronze badges
15
I was recently faced with the same problem, but in my case, I remember my password quite alright, but it kept on giving me the same error. I tried so many solutions, but still none helped. Then I tried this:
mysql -u root -p
After which it asks you for a password like this
Enter password:
And then I typed in the password I used. That’s all.
answered Mar 21, 2018 at 22:22
4
I was able to solve this problem by executing this statement
sudo dpkg-reconfigure mysql-server-5.5
Which will change the root password.
answered Mar 18, 2014 at 3:37
DivzDivz
1,3832 gold badges8 silver badges6 bronze badges
8
You have to reset the password! Steps for Mac OS X (tested and working) and Ubuntu:
Stop MySQL using
sudo service mysql stop
or
sudo /usr/local/mysql/support-files/mysql.server stop
Start it in safe mode:
sudo mysqld_safe --skip-grant-tables --skip-networking
(the above line is the whole command)
This will be an ongoing command until the process is finished, so open another shell/terminal window, log in without a password:
mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD("password") WHERE User="root";
As per @IberoMedia’s comment, for newer versions of MySQL, the field is called authentication_string
:
mysql> UPDATE mysql.user SET authentication_string=PASSWORD("password") WHERE User="root";
Start MySQL using:
sudo service mysql start
or
sudo /usr/local/mysql/support-files/mysql.server start
Your new password is ‘password’.
Note: for version of MySQL > 5.7 try this:
update mysql.user set authentication_string="password" where user="root";
answered Sep 17, 2014 at 6:44
tk_tk_
16.3k8 gold badges80 silver badges90 bronze badges
13
It happens when your password is missing.
Steps to change the password when you have forgotten it:
-
Stop MySQL Server (on Linux):
sudo systemctl stop mysql
-
Start the database without loading the grant tables or enabling networking:
sudo mysqld_safe --skip-grant-tables --skip-networking &
The ampersand at the end of this command will make this process run in the background, so you can continue to use your terminal and run
mysql -u root
(as root). It will not ask for a password.If you get error like as below:
2018-02-12T08:57:39.826071Z mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists. mysql -u root ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) [1]+ Exit 1
-
Make MySQL service directory.
sudo mkdir /var/run/mysqld
Give MySQL user permission to write to the service directory.
sudo chown mysql: /var/run/mysqld
-
Run the same command in step 2 to run MySQL in background.
-
Run
mysql -u root
. You will get the MySQL console without entering a password.Run these commands
FLUSH PRIVILEGES;
For MySQL 5.7.6 and newer
ALTER USER 'root'@'localhost' IDENTIFIED BY 'new_password';
For MySQL 5.7.5 and older
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('new_password');
If the ALTER USER command doesn’t work use:
UPDATE mysql.user SET authentication_string = PASSWORD('new_password') WHERE User = 'root' AND Host = 'localhost';
Now exit
-
To stop the instance started manually:
sudo kill `cat /var/run/mysqld/mysqld.pid`
-
Restart MySQL
sudo systemctl start mysql
answered Feb 12, 2018 at 14:25
4
At the initial start up of the server the following happens, given that the data directory of the server is empty:
- The server is initialized.
- SSL certificate and key files are generated in the data directory.
- The validate_password plugin is installed and enabled.
- The superuser account ‘root’@’localhost’ is created. The password for the superuser is set and stored in the error log file.
To reveal it, use the following command:
shell> sudo grep 'temporary password' /var/log/mysqld.log
Change the root password as soon as possible by logging in with the generated temporary password and set a custom password for the superuser account:
shell> mysql -u root -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass5!';
answered Mar 23, 2017 at 5:17
LahiruLahiru
1,37812 silver badges17 bronze badges
8
If the problem still exists, try to force changing the password:
/etc/init.d/mysql stop
mysqld_safe --skip-grant-tables &
mysql -u root
Set up a new MySQL root user password:
use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
flush privileges;
quit;
Stop the MySQL server:
/etc/init.d/mysql stop
Start the MySQL server and test it:
mysql -u root -p
answered May 20, 2014 at 13:34
Yasin HassanienYasin Hassanien
4,0451 gold badge20 silver badges17 bronze badges
6
If none of the other answers work for you, and you received this error:
mysqld_safe Logging to '/var/log/mysql/error.log'.
mysqld_safe Directory '/var/run/mysqld' for UNIX socket file don't exists.
[1]+ Exit 1 sudo mysqld_safe --skip-grant-tables
Follow the below commands step by step until you reset your password:
# Stop your server first
sudo service mysql stop
# Make the MySQL service directory.
sudo mkdir /var/run/mysqld
# Give MySQL permission to work with the created directory
sudo chown mysql: /var/run/mysqld
# Start MySQL, without permission and network checking
sudo mysqld_safe --skip-grant-tables --skip-networking &
# Log in to your server without any password.
mysql -u root mysql
# Update the password for the root user:
UPDATE mysql.user SET authentication_string=PASSWORD('YourNewPasswordBuddy'), plugin='mysql_native_password' WHERE User='root' AND Host='localhost';
# If you omit (AND Host='localhost') section, it updates
# the root password regardless of its host
FLUSH PRIVILEGES;
EXIT;
# Kill the mysqld_safe process
sudo service mysql restart
# Now you can use your new password to log in to your server
mysql -u root -p
# Take note for remote access. You should create a remote
# user and then grant all privileges to that remote user
answered Apr 16, 2019 at 11:39
MehdiMehdi
3,7843 gold badges36 silver badges65 bronze badges
1
I came across this very annoying problem and found many answers that did not work. The best solution I came across was to completely uninstall MySQL and reinstall it. On reinstall you set a root password and this fixed the problem.
sudo apt-get purge mysql-server mysql-client mysql-common mysql-server-core-5.5 mysql-client-core-5.5
sudo rm -rf /etc/mysql /var/lib/mysql
sudo apt-get autoremove
sudo apt-get autoclean
I found this code elsewhere, so I don’t take any credit for it. But it works. To install MySQL after uninstalling it, I think DigitalOcean has a good tutorial on it. Checkout my gist for this.
How to install MySQL on Ubuntu (which works)
answered Feb 9, 2017 at 21:05
JamesDJamesD
5815 silver badges10 bronze badges
0
I am using Ubuntu 16.04 (Xenial Xerus) and installed MySQL 5.7.
I had the same issue
Login denied for root user.
I tried the below steps:
-
dpkg --get-selections | grep mysql
(to get the version of MySQL). -
dpkg-reconfigure mysql-server-5.7
-
mysql -u root -p
Without -p that doesn’t prompt you to ask password. Once you are in, you can create a user with a password by following steps:
CREATE USER 'your_new_username'@'your-hostname' IDENTIFIED BY 'your-password';
GRANT ALL PRIVILEGES ON *.* to 'your_new_username'@'your-hostname' WITH GRANT OPTION;
Exit from the root and log in from the <name> you gave above.
mysql -u <your_new_username> -p
For some reason still just typing MySQL does not work. At all. I suggest to make it a habit to use mysql -u <name> -p
.
answered Jun 21, 2017 at 15:21
1
In the terminal, just enter:
mysql -u root -p
Then it will ask the password from you.
answered Jul 8, 2019 at 21:24
1
I installed MySQL as root user (
$SUDO
) and got this same issue
Here is how I fixed it:
-
sudo cat /etc/mysql/debian.cnf
This will show details as:
# Automatically generated for Debian scripts. DO NOT TOUCH! [client] host = localhost user = debian-sys-maint password = GUx0RblkD3sPhHL5 socket = /var/run/mysqld/mysqld.sock [mysql_upgrade] host = localhost user = debian-sys-maint password = GUx0RblkD3sPhHL5 socket = /var/run/mysqld/mysqld.sock
Above we can see the password. But we are just going to use
(GUx0RblkD3sPhHL5)
that in the prompt. -
`mysql -u debian-sys-maint -p
Enter password: `
Now provide the password (GUx0RblkD3sPhHL5).
-
Now
exit
from MySQL and log in again as:`mysql -u root -p
Enter password: `
Now provide the new password. That’s all. We have a new password for further uses.
It worked for me.
answered Sep 17, 2019 at 12:30
S.YadavS.Yadav
4,1733 gold badges37 silver badges42 bronze badges
For those for whom the current answers didn’t work can try this (tested on macOS):
mysql -h localhost -u root -p --protocol=TCP
After this, a password will be asked from you and you should use your OS user password. Then when you get into MySQL you can run:
select Host, User from mysql.user;
And you should see:
MySQL [(none)]> select Host, User from mysql.user;
+-----------+------------------+
| Host | User |
+-----------+------------------+
| localhost | mysql.infoschema |
| localhost | mysql.session |
| localhost | mysql.sys |
| localhost | root |
+-----------+------------------+
And from here you can change the configurations and edit the password or modify the grants.
answered Nov 25, 2020 at 19:29
EricEric
4606 silver badges15 bronze badges
3
Please read the official documentation: MySQL: How to Reset the Root Password
If you have access to a terminal:
MySQL 5.7.6 and later:
mysql
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
MySQL 5.7.5 and earlier:
mysql
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
answered Aug 10, 2015 at 10:05
d.danailovd.danailov
9,5444 gold badges51 silver badges36 bronze badges
2
Year 2021.
Answer for Ubuntu 20.04 (Focal Fossa) (maybe other distributions as well).
After days of wandering around… and having none of those answers working for me, I did this and it worked!
Always in a Bash shell:
sudo systemctl disable mysql
In order to stop the daemon from starting on boot.
sudo apt purge mysql-server
and
sudo apt purge mysql-community-server*
There, it warns you you’ll erase configuration files… so it’s working! Because those are the ones making trouble!
sudo apt autoremove
The command sudo apt autoremove deletes all the left behind packages.
Then (maybe it’s optional, but I did it) reboot.
Also, I downloaded mysql-server-8.0 from the official MySQL webpage:
sudo apt install mysql-server
A signal that it’s working is that when you enter the command above, the system asks you to enter the root password.
Finally:
mysql -u root -p
And the password you entered before.
CodeWeis
8466 silver badges19 bronze badges
answered Jul 26, 2021 at 3:48
DiegoMMFDiegoMMF
1292 silver badges3 bronze badges
I am using mysql-5.7.12-osx10.11-x86_64.dmg on Mac OS X.
The installation process automatically sets up a temporary password for the root user. You should save the password. The password can not be recovered.
Follow the instructions:
- Go to
cd /usr/local/mysql/bin/
- Enter the temporary password (which would look something like, «tsO07JF1=>3»)
- You should get the
mysql>
prompt. - Run,
SET PASSWORD FOR 'root'@'localhost' = PASSWORD('{YOUR_PASSWORD}');
If you wish to set your password: «root» then the command would be,SET PASSWORD FOR 'root'@'localhost' = PASSWORD('root');
- Run
ALTER USER 'root'@'localhost' PASSWORD EXPIRE NEVER;
- Run
exit
- Run
./mysql -u root -p
- Type your password. In my case I would type, «root» (without quote)
- That’s all.
For convenience, you should add "/usr/local/mysql/bin"
to your PATH environment variable.
Now from anywhere you can type ./mysql -u root -p
and then type the password and you will get the mysql>
prompt.
answered May 30, 2016 at 11:14
tausiqtausiq
9371 gold badge13 silver badges23 bronze badges
The answer may sound silly, but after wasting hours of time, this is how I got it to work:
mysql -u root -p
I got the error message
ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: YES)
Even though I was typing the correct password (the temporary password you get when you first install MySQL).
I got it right when I typed in the password when the password prompt was blinking.
answered Dec 6, 2017 at 3:31
Amit KumarAmit Kumar
8042 gold badges11 silver badges16 bronze badges
1
If you have MySQL as part of a Docker image (say on port 6606) and an Ubuntu install (on port 3306) specifying the port is not enough:
mysql -u root -p -P 6606
will throw:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)
as it’s trying to connect to localhost by default, specifying your local IP address fixes the issue:
mysql -u root -p -P 6606 -h 127.0.0.1
answered Nov 19, 2019 at 11:36
botrisbotris
1612 silver badges2 bronze badges
If the problem still exists, try to force changing the password.
Stop MySQL Server (on Linux):
/etc/init.d/mysql stop
Stop MySQL Server (on Mac OS X):
mysql.server stop
Start the mysqld_safe daemon with —skip-grant-tables:
mysqld_safe --skip-grant-tables &
mysql -u root
Set up a new MySQL root user password:
use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
flush privileges;
quit;
Stop MySQL Server (on Linux):
/etc/init.d/mysql stop
Stop MySQL Server (on Mac OS X):
mysql.server stop
Start the MySQL server service and test to log in by root:
mysql -u root -p
answered Jul 26, 2017 at 2:19
Max YaoMax Yao
7116 silver badges7 bronze badges
I also came across the same problem. I did:
-
Open your cmd
-
Navigate to C:Program FilesMySQLMySQL Server 8.0bin>
(where MySQL Server 8.0 may be different depending on the server you installed) -
Then put the following command
mysql -u root -p
-
It will prompt for the password… simply hit Enter, as sometimes the password you entered while installing is changed by to blank.
Now you can simply access the database.
This solution worked for me on the Windows platform.
answered Nov 8, 2019 at 17:08
While the top answer (with mysqladmin) worked on macOS v10.15 (Catalina), it did not work on Ubuntu. Then I tried many of the other options, including a safe start for MySQL, but none worked.
Here is one that does:
At least for the version I got 5.7.28-0ubuntu0.18.04.4
answers were lacking IDENTIFIED WITH mysql_native_password
. 5.7.28 is the default on the current LTS and thus should be the default for most new new systems (till Ubuntu 20.04 (Focal Fossa) LTS comes out).
I found Can’t set root password MySQL Server and now applied
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_pass_here';
which does work.
answered Dec 9, 2019 at 10:43
arntgarntg
1,54714 silver badges12 bronze badges
By default, the password will be null, so you have to change the password by doing the below steps.
Connect to MySQL
root# mysql
Use mysql
mysql> update user set password=PASSWORD('root') where User='root';
Finally, reload the privileges:
mysql> flush privileges;
mysql> quit
Just one line and it solved my issue.
sudo dpkg-reconfigure mysql-server-5.5
answered May 11, 2016 at 21:51
In Ubuntu 16.04 (Xenial Xerus) and MySQL version 5.7.13, I was able to resolve the problem with the steps below:
-
Follow the instructions from section B.5.3.2.2 Resetting the Root Password: Unix and Unix-Like Systems
MySQL 5.7 reference manual -
When I tried
#sudo mysqld_safe --init-file=/home/me/mysql-init &
it failed. The error was in /var/log/mysql/error.log:2016-08-10T11:41:20.421946Z 0 [Note] Execution of init_file '/home/me/mysql/mysql-init' started. 2016-08-10T11:41:20.422070Z 0 [ERROR] /usr/sbin/mysqld: File '/home/me/mysql/mysql-init' not found (Errcode: 13 - Permission denied) 2016-08-10T11:41:20.422096Z 0 [ERROR] Aborting
The file permission of mysql-init was not the problem. We need to edit AppArmor permissions.
-
Edit by
sudo vi /etc/apparmor.d/usr.sbin.mysqld
.... /var/log/mysql/ r, /var/log/mysql/** rw, # Allow user init file /home/pranab/mysql/* r, # Site-specific additions and overrides. See local/README for details. #include <local/usr.sbin.mysqld> }
-
Do
sudo /etc/init.d/apparmor reload
-
Start mysqld_safe again. Try step 2 above. Check file /var/log/mysql/error.log. Make sure there is no error and the mysqld is successfully started.
-
Run
mysql -u root -p
Enter password:
Enter the password that you specified in mysql-init. You should be able to log in as root now.
-
Shutdown mysqld_safe by
sudo mysqladmin -u root -p shutdown
-
Start mysqld the normal way by
sudo systemctl start mysql
answered Aug 10, 2016 at 13:37
codegencodegen
791 silver badge2 bronze badges
The error that I faced was:
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
It was a problem with the port running on.
By default, MySQL is running on port 3306.
You can check that on by running
-
in a 32-bit system:
sudo /opt/lampp/manager-linux.run
-
in a 64-bit system:
sudo /opt/lampp/manager-linux-x64.run
and click on the Configure button.
In my case the port was running on 3307, and I used the command
mysql -u root -p -P 3307 -h 127.0.0.1
answered Mar 12, 2020 at 16:20
RochaaPRochaaP
3055 silver badges14 bronze badges
Copied from this link, I had the same problem and this solved the problem. After we add a password for the database, we need to add -p
(password-based login), and then enter the password. Otherwise, it will return this error:
mysql -u root -p
answered Nov 5, 2020 at 8:07
Because your error message says «PASSWORD: YES» this means you are are using the wrong password. This happened to me also. Luckily I remembered my correct password, and was able to make the DB connection work.
answered May 31, 2022 at 22:17
In recent MySQL versions there isn’t any password
in the mysql.user
table.
So you need to execute ALTER USER
. Put this one line command into the file.
ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';
And execute it as an init file (as the root or mysql user):
mysqld_safe --init-file=/home/me/mysql-init &
MySQL server need to be stopped to start mysqld_safe
.
Also, there may be a problem with AppArmor permissions to load this init file. Read more in AppArmor and MySQL.
answered Jun 9, 2016 at 15:06
If you haven’t set password yet, then run mysql -uroot
. It works for me.
answered Aug 16, 2018 at 11:10
ah bonah bon
9,19710 gold badges60 silver badges143 bronze badges
On Mac, if you have a problem in logging in with the first password you were given in installation, maybe you can just simply kill the MySQL process and then try.
So:
-
run the following command to find the PID of MySQL:
ps -aef | grep mysql | grep -v grep
-
kill the process:
kill -15 [process id]
Then you can log in with the initial password using this command:
mysql -uroot -p
Which asks you to enter your password. Just enter the initial password.
answered Jan 19, 2019 at 9:22
Ошибка: Access denied for user ‘root’@’localhost’ (Using password: YES и NO)
При работе с системой MySQL могут возникнуть самые разные ошибки, и на этапе освоения программы разобраться с ними может быть сложно. Одна из наиболее распространенных проблем — ошибка 1045, которая сопровождается сообщением Access denied for user ‘root’@’localhost’ (Using password: YES и NO). Сегодня я расскажу, как ее исправить.
Понять суть проблемы можно, переведя сообщение об ошибке на русский язык. Означает оно, что пользователю с именем root на машине localhost запрещен доступ к БД при использовании пароля или без него.
Причины ошибки Access denied for user ‘root’@’localhost’
Чтобы свободно получить доступ в MySQL, должно совпасть три параметра, описывающих пользователя базы данных — имя, название машины и пароль. Если есть какие-то несовпадения, доступ будет запрещен. Самая простая причина проблемы — неправильный ввод пароля. Кроме этого, вызывать ошибку может неправильный синтаксис.
В системе MySQL нет простой зависимости имя пользователя – пароль, название хоста играет важную роль в получении доступа к БД. Оно может иметь вид IP-адреса, доменного имени, ключевого слова (например, localhost) или символа, объединяющего несколько машин в группу (например, % — любой хост, кроме локального).
Наиболее распространенные ошибки при обращении к БД:
- При присвоении прав новому пользователю не был указан адрес машины, с которой он может подключаться. В таком случае ему автоматически будет разрешено пользоваться БД с любого хоста, кроме локального, и при попытке подключения с localhost возникнет ошибка доступа.
- Неправильно расставленные кавычки. Если при создании пользователя написать ‘username@localhost’, это будет значить, что username@localhost может подключаться с любой машины, кроме локальной, а не что username может подключаться с компьютера localhost. Логин пользователя и имя машины должны иметь свою пару кавычек.
- Использование пароля при его отсутствии в базе данных.
В зависимости от того, при каком способе подключения к БД возникает ошибка Access denied for user ‘root’@’localhost’ (Using password: YES или NO), используются разные методы решения проблемы.
Если ошибка Access denied for user появляется с указанием Using password: YES, проблема заключается в неправильном вводе пароля. Проверить это можно, открыв таблицу mysql.user, в которой хранятся данные обо всех пользователях.
Порядок действий таков:
- Откройте таблицу пользователей.
- Проверьте, существует ли пользователь root с хостом localhost. Если он есть, смотрите на поле «password». Если там пусто, зайти в базу можно без ввода пароля. Если там что-то есть, значит, вы вводите неправильный пароль.
- Смените пароль командой SET PASSWORD.
- Если пользователя 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
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