Access denied for user root localhost using password no windows

I'm trying to run WordPress in my Windows desktop and it needs MySQL. I install everything with Web Platform Installer which is provided by Microsoft. I never set a root password for MySQL and in the

I’m trying to run WordPress in my Windows desktop and it needs MySQL.

I install everything with Web Platform Installer which is provided by Microsoft. I never set a root password for MySQL and in the final step of installing WordPress, it asks for a MySQL server password.

What is the default password for root (if there is one) and how to change it?

I tried:

mysql -u root password '123'

But it shows me:

Access denied for user 'root@localhost' (using password:NO)

After this I try:

mysql -u root -p

However, it asks for a password which I don’t have.


Update: as Bozho suggested, I did the following:

  1. I stopped the MySQL Service from Windows services

  2. Opened CMD

  3. Changed the location to c:program filesmysqlbin

  4. Executed the command below

    mysqld --defaults-file="C:\program files\mysql\mysql server 5.1\my.ini" --init-files=C:\root.txt

  5. The command ran with a warning about character set which I mentioned below

  6. I start the MySQL service from Windows services

  7. I write in the command line

    mysql -u root -p
    EnterPassword: 123 // 123 was the password

  8. The command line shows the following error

    Access denied for user 'root@localhost' (using password:**YES**)

How do I solve this?

user's user avatar

user

4,3135 gold badges17 silver badges34 bronze badges

asked Jun 8, 2010 at 5:53

Nasser Hadjloo's user avatar

Nasser HadjlooNasser Hadjloo

12.1k15 gold badges69 silver badges99 bronze badges

4

for this kind of error; you just have to set new password to the root user as an admin. follow the steps as follows:

[root ~]# mysql -u root
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password:NO)
  1. Stop the service/daemon of mysql running

     [root ~]# service mysql stop   
     mysql stop/waiting
    
  2. Start mysql without any privileges using the following option;
    This option is used to boot up and do not use the privilege system of MySQL.

     [root ~]# mysqld_safe --skip-grant-tables &
    

At this moment, the terminal will seem to halt. Let that be, and use new terminal for next steps.

  1. enter the mysql command prompt

     [root ~]# mysql -u root
     mysql> 
    
  2. Fix the permission setting of the root user ;

     mysql> use mysql;
     Database changed
     mysql> select * from  user;
     Empty set (0.00 sec)
     mysql> truncate table user;
     Query OK, 0 rows affected (0.00 sec)
     mysql> flush privileges;
     Query OK, 0 rows affected (0.01 sec)
     mysql> grant all privileges on *.* to root@localhost identified by 'YourNewPassword' with grant option;
     Query OK, 0 rows affected (0.01 sec)
    

*if you don`t want any password or rather an empty password

    mysql> grant all privileges on *.* to root@localhost identified by '' with grant option;
    Query OK, 0 rows affected (0.01 sec)*
    mysql> flush privileges;
    Query OK, 0 rows affected (0.00 sec)

Confirm the results:

    mysql> select host, user from user;
+-----------+------+
| host      | user |
+-----------+------+
| localhost | root |
+-----------+------+
1 row in set (0.00 sec)
  1. Exit the shell and restart mysql in normal mode.

     mysql> quit;
     [root ~]# kill -KILL [PID of mysqld_safe]
     [root ~]# kill -KILL [PID of mysqld]
     [root ~]# service mysql start
    
  2. Now you can successfully login as root user with the password you set

      [root ~]# mysql -u root -pYourNewPassword 
      mysql> 
    

Ryan M's user avatar

Ryan M

17.3k30 gold badges60 silver badges70 bronze badges

answered May 29, 2014 at 2:37

user2977819's user avatar

8

You can reset your root password. Have in mind that it is not advisable to use root without password.

answered Jun 8, 2010 at 5:54

Bozho's user avatar

BozhoBozho

582k141 gold badges1052 silver badges1136 bronze badges

4

1) You can set root password by invoking MySQL console. It is located in

C:wampbinmysqlmysql5.1.53bin by default.

Get to the directory and type MySQL. then set the password as follows..

    > SET PASSWORD FOR root@localhost = PASSWORD('new-password');

2) You can configure wamp’s phpmyadmin application for root user by editing

C:wampappsphpmyadmin3.3.9config.inc.php 

Note :- if you are using xampp then , file will be located at

C:xamppphpMyadminconfig.inc.php

It looks like this:

        $cfg['Servers'][$i]['verbose'] = 'localhost';
        $cfg['Servers'][$i]['host'] = 'localhost';
        $cfg['Servers'][$i]['port'] = '';
        $cfg['Servers'][$i]['socket'] = '';
        $cfg['Servers'][$i]['connect_type'] = 'tcp';
        $cfg['Servers'][$i]['extension'] = 'mysqli';
        $cfg['Servers'][$i]['auth_type'] = 'config';
        $cfg['Servers'][$i]['user'] = 'root';
        $cfg['Servers'][$i]['password'] = 'YOURPASSWORD';
        $cfg['Servers'][$i]['AllowNoPassword'] = false;

The error «Access denied for user ‘root@localhost’ (using password:NO)»
will be resolved when you set $cfg['Servers'][$i]['AllowNoPassword'] to false

If you priviously changed the password for ‘root@localhost’, then you have to do 2 things to solve the error «Access denided for user ‘root@localhost'»:

  1. if [‘password’] have a empty quotes like ‘ ‘ then put your password between quotes.
  2. change the (using password:NO) to (using password:YES)

This will resolve the error.

Note: phpmyadmin is a separate tool which comes with wamp.
It just provide a interface to MySQL. if you change my sql root’s password, then you should change the phpmyadmin configurations. Usually phpmyadmin is configured to root user.

Andreas's user avatar

Andreas

6,4152 gold badges35 silver badges46 bronze badges

answered Dec 25, 2012 at 8:35

yellobird's user avatar

yellobirdyellobird

2793 silver badges3 bronze badges

2

Use mysql -u root -p
It will ask for password, insert password and enter.

answered May 16, 2019 at 11:10

Vikash Kumar's user avatar

2

I was getting the same error on OS X El captain.
Mysql version 5.7 . I was able to connect to mysql with root after executing these steps.

Stop the mysql server

sudo mysql.server stop

Start mysql in safe mode

sudo mysqld_safe --skip-grant-tables

Using mysqld, Change the database to mysql and update the details for user ‘root’.

show databases;
use mysql;
UPDATE mysql.user 
    SET authentication_string = PASSWORD('MyNewPass'), password_expired = 'N'
    WHERE User = 'root' AND Host = 'localhost';
exit;

After that kill the ‘mysqld_safe’ process and start mysql normally. You should be able to login to mysql using root and new password. SQL docs for more details

answered Jul 5, 2016 at 10:54

Sushantkumar M's user avatar

Simply edit my.ini file in C:xamppmysqlbin path. Just add:

skip-grant-tables

line in between lines of # The MySQL server [mysqld] and port=3306. Then restart the MySQL server.

Looks like:

Screenshot

Stephen Rauch's user avatar

Stephen Rauch

46.7k31 gold badges109 silver badges131 bronze badges

answered Mar 16, 2018 at 0:19

Ryan Oscar's user avatar

Ryan OscarRyan Oscar

2791 gold badge4 silver badges19 bronze badges

1

For some information I’ve get error after changing password:

Access denied for user ‘root’@’localhost’ (using password: NO)

Access denied for user ‘root’@’localhost’ (using password: YES)

In both cases there was error.

But the thing is after that I’ve tried it with

mysql -uroot -ppassword instead of

mysql -u root -p password -> with spaces between -uroot and -ppassword so maybe if someone get trouble can try this way.

Community's user avatar

answered Mar 1, 2020 at 18:39

profiile_samir's user avatar

Make sure the MySQL service is running on your machine, then follow the instructions from MySQL for initially setting up root (search for ‘windows’ and it will take you to the steps for setting up root):

Securing the Initial MySQL Account

Kuro Neko's user avatar

answered Jun 8, 2010 at 5:56

sholsapp's user avatar

sholsappsholsapp

15.2k10 gold badges47 silver badges65 bronze badges

3

Another solution if someone gets the error The specified password for user account ‘root’ is not valid, or failed to connect to the database server also with the right password, is the follow

•In the Windows registry, delete the mysql_pwd reg key under HKCUSoftwareMicrosoftWebPlatformInstaller

•Unistall older version of MySQL .NET connector

•Download and install the latest MySql .NET Connector.

answered Apr 5, 2014 at 18:50

Silverstorm's user avatar

SilverstormSilverstorm

14.7k2 gold badges36 silver badges52 bronze badges

1

  1. Change the password from config.inc.php present in C:xamppphpMyAdmin.
  2. Type mysql -u root -p in the command prompt.
  3. You will be asked to enter the password. Enter that password which you updated in the config.inc.php.

double-beep's user avatar

double-beep

4,84916 gold badges32 silver badges41 bronze badges

answered May 19, 2020 at 15:39

user12682744's user avatar

1

In your code replace the ‘root’ with your Server username and password with your server password.
For example if you have DB and your php files on the server http://www.example.com
then obviously you would have to enter into this server site using your username and password.

answered Jun 22, 2015 at 19:21

Pir Fahim Shah's user avatar

Pir Fahim ShahPir Fahim Shah

10.3k1 gold badge79 silver badges79 bronze badges

For MySQL 5.7. These are the below steps:

Stop your MySQL server completely. This can be done by accessing the Services window inside Windows XP and Windows Server 2003, where you can stop the MySQL service.

Open your MS-DOS command prompt using «cmd» inside the Run window. Inside it navigate to your MySQL bin folder, such as C:MySQLbin using the cd command.

Execute the following command in the command prompt: mysqld.exe -u root —skip-grant-tables

Leave the current MS-DOS command prompt as it is, and open a new MS-DOS command prompt window.

Navigate to your MySQL bin folder, such as C:MySQLbin using the cd command.

Enter mysql and press enter.

You should now have the MySQL command prompt working. Type use mysql; so that we switch to the «mysql» database.

Execute the following command to update the password:

update user set authentication_string=password(‘1111′) where user=’root’;

answered Dec 1, 2016 at 2:30

Katie's user avatar

KatieKatie

4527 silver badges18 bronze badges

0

Some times it just happens due to installation of Wamp or changing of password options of root user.
One can use privilages—>root (user) and then set password option to NO to run the things without any password OR set the password and use it in the application.

Pieter Goosen's user avatar

answered Feb 5, 2015 at 8:07

Sayyad's user avatar

If you are using XAMPP just go to C:xamppphpMyAdmin and then open config.inc.php find $cfg['Servers'][$i]['password'] = '' line and put your password there.

answered Aug 4, 2018 at 6:22

Ajay Rawat's user avatar

Ajay RawatAjay Rawat

1672 silver badges10 bronze badges

if you changed the port to non standard one, then you need to specify it:

$connection = mysqli_connect('localhost:3308', 'root', '', 'loginapp');

Kuro Neko's user avatar

answered May 21, 2020 at 18:54

Mitchell Yuen's user avatar

If the root account exists but has no password, connect to the server as root using no password, then assign a password. This was my situation when I encountered this issue.

Connect to the server as root using no password:

$> mysql -u root --skip-password

Assign a password:

mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'root-password';

I was able to solve my problem this way. Hope this helps someone who encounters a similar issue in the future. Cheers!

Reference: https://dev.mysql.com/doc/refman/8.0/en/default-privileges.html

answered Jan 9, 2022 at 17:10

K M Rakibul Islam's user avatar

K M Rakibul IslamK M Rakibul Islam

33.3k12 gold badges88 silver badges107 bronze badges

mysqladmin -u root -p password

enter your current password

then

enter your new password

0bserver07's user avatar

0bserver07

3,2901 gold badge28 silver badges56 bronze badges

answered Oct 7, 2013 at 16:26

djrconcepts's user avatar

djrconceptsdjrconcepts

6255 silver badges6 bronze badges

2

It happens because of the security reason.

try with the following

mysql -u root -p    

click enter and enter the password and try again

answered Apr 27, 2021 at 8:30

janadari ekanayaka's user avatar

0

This “access denied” error is one of the most common errors you’ll get when working with MySQL.

Learn how to fix it, and see a range of solutions if the suggested fix does not work, in this article.

When you try to connect to a MySQL database on your own computer (called “localhost”), you may get this error:

Access denied for user 'root'@'localhost' (using password: YES)

You might get an error code in front of it:

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)

You might also get the error with “using password no”:

Access denied for user 'root'@'localhost' (using password: NO)

You’ll see this if you log into MySQL using the command line:

mysql -u root -p

You might also see this if you log in to MySQL using an IDE such as MySQL Workbench. Or even if you use phpMyAdmin.

What does this mean? How can you fix it?

There are a few solutions to this, which I’ve detailed below. Try one, and if it doesn’t work, try another one.

Also a tip for logging in: don’t enter your password in the command line itself, because this will be stored in your command history. Use the -p option, as mentioned above, and then you’ll be prompted to enter the password.

Solution 1: Sudo then Change Password

If you get the “access denied” error, one way to solve it is by using sudo to log in to mysql and change the root password.

Step 1: Open the command line on your system.

Step 2: Open mysql using the sudo command:

sudo mysql

Step 3: Enter the password for this account.

Step 4: Change the auth_plugin to mysql_native_password, and the password for the root account, in a single command:

ALTER USER 'root'@'localhost'
IDENTIFIED WITH mysql_native_password BY 'your_new_password';

Substitute the word your_new_password with a new secure password that you want to use for the root account.

The mysql_native_password method is a traditional method of authentication and will allow you to login.

Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:

FLUSH PRIVILEGES;

Step 6: You can confirm that the new authentication method, or plugin, is used by selecting from the mysql.user table.

SELECT user, plugin
FROM mysql.user

Results:

user plugin
root mysql_native_password

Step 7: Exit the console by pressing CTRL + D or typing exit.

exit;

Step 8: Log in to mysql using the root account and the new password you set, which should work:

mysql -u root -p

You should now be logged in to the root account in mysql.

Solution 2: Edit My.cnf File

If the above solution did not work, you may need to edit the mysql.cnf file to allow for changes to the root account.

Step 1: Open the my.cnf file. This may be stored in:

/etc/my.cnf
/etc/mysql/my.cnf

If you’re not sure where it is, search your MySQL installation folder (e.g. on Windows or Mac) for the file.

If you don’t have a my.cnf file (MacOS does not include one by default). You can create one in the /etc folder if you like.

Step 2: Add the word skip-grant-tables under the word [mysqld]. Your file may look like this:

[mysqld]
skip-grant-tables

Step 3: Restart the MySQL server.

Step 4: Login to the root account:

mysql -u root -p

Step 5: Flush the privileges, which tells the server to refresh the grant tables and apply your changes, with this command:

FLUSH PRIVILEGES;

Step 6: Set a new password for the account:

ALTER USER 'root'@'localhost' IDENTIFIED BY 'your_new_password';

Substitute the word your_new_password with a new secure password that you want to use for the root account.

Step 7: Open the my.cnf file you opened in step 1, and remove the line about skip-grant-tables, and save the file.

Step 8: Restart the MySQL server again.

Step 9: Log in to the root account again:

mysql -u root -p

You should now be able to log in successfully with your new password and not get an error.

Conclusion

Either of these two solutions should hopefully solve the problem for you, and you should no longer get the error “Access denied for user ‘root’@’localhost’”.

If you have any questions, feel free to use the comments section below.

grep 'temporary password' /var/log/mysqld.log
Sort date (newest date)

You may see something like this;

[root@SERVER ~]# grep 'temporary password' /var/log/mysqld.log
2016-01-16T18:07:29.688164Z 1 [Note] A temporary password is generated for root@localhost: O,k5.marHfFu
2016-01-22T13:14:17.974391Z 1 [Note] A temporary password is generated for root@localhost: b5nvIu!jh6ql
2016-01-22T15:35:48.496812Z 1 [Note] A temporary password is generated for root@localhost: (B*=T!uWJ7ws
2016-01-22T15:52:21.088610Z 1 [Note] A temporary password is generated for root@localhost: %tJXK7sytMJV
2016-01-22T16:24:41.384205Z 1 [Note] A temporary password is generated for root@localhost: lslQDvgwr3/S
2016-01-22T22:11:24.772275Z 1 [Note] A temporary password is generated for root@localhost: S4u+J,Rce_0t
[root@SERVER ~]# mysql_secure_installation

Securing the MySQL server deployment.

Enter password for user root: 

The existing password for the user account root has expired. Please set a new password.

New password: 

Re-enter new password:

If you see it says

... Failed! Error: Your password does not satisfy the current policy requirements
That means your password needs to have a character such as ! . # - etc...
mix characters well, upper case, lower case, ! . , # etc...

New password: 

Re-enter new password: 
The 'validate_password' plugin is installed on the server.
The subsequent steps will run with the existing configuration
of the plugin.
Using existing password for root.

Estimated strength of the password: 100 
Change the password for root ? ((Press y|Y for Yes, any other key for No) : Y

New password: 

Re-enter new password: 

Estimated strength of the password: 100 
Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
By default, a MySQL installation has an anonymous user,
allowing anyone to log into MySQL without having to have
a user account created for them. This is intended only for
testing, and to make the installation go a bit smoother.
You should remove them before moving into a production
environment.

Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y
Success.


Normally, root should only be allowed to connect from
'localhost'. This ensures that someone cannot guess at
the root password from the network.

Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y
Success.

By default, MySQL comes with a database named 'test' that
anyone can access. This is also intended only for testing,
and should be removed before moving into a production
environment.


Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y
 - Dropping test database...
Success.

 - Removing privileges on test database...
Success.

Reloading the privilege tables will ensure that all changes
made so far will take effect immediately.

Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y
Success.

All done! 
[root@SERVER ~]# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 11
Server version: 5.7.10 MySQL Community Server (GPL)

Watch the last 10 minutes of this video, it teaches you how you do it.

Дата: 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. Перепечатка в интернет-изданиях разрешается только с указанием автора и прямой ссылки на оригинальную статью. Перепечатка в бумажных изданиях допускается только с разрешения редакции.

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

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

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

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

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

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

Root cause

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

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

How to reproduce this issue

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

mysql -u root 

Solution 1

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

$>mysql -u root -p 
Enter password:

Solution 2

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

$> mysqld --skip-grant-tables

$> mysql -u root mysql

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

mysql> flush privileges;

Solution 3

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

$> mysqld --skip-grant-tables

$> mysql -u root mysql

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

mysql> flush privileges;

Solution 4

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

$> mysqld --skip-grant-tables

$> mysql -u root mysql

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

mysql> FLUSH PRIVILEGES;

mysql> exit

start mysql again

Solution 5

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

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

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

mysql> FLUSH PRIVILEGES;

MySQL 1045 error Access DeniedDuring 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:

  1. Stop the instance
  2. 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]
  3. Start the instance
  4. Access with root user (mysql -uroot -hlocalhost); 
  5. 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’;”

  6. Stop the instance
  7. Edit my.cnf and remove skip-grant-tables and skip-networking
  8. Start MySQL again
  9. 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

In this MySql tutorial we will solve very important MySql error —  How to resolve ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: NO) /  (using password: YES) in MySql.

ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: NO) in MySql>

when you try to login to root user using mysql -u root. You may face ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: NO)

C:Program FilesMySQLMySQL Server 5.6bin>mysql -u root

ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: NO)

The default password  for user root is blank (i.e. an empty string). If in case it has never been changed then you may simply login to root user using mysql -u root command.

ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: YES) in MySql >

when you try to login to root user using  mysql -u root -p, and if you enter wrong password, you may face ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: YES)

C:Program FilesMySQLMySQL Server 5.6bin>mysql -u root -p

Enter password: ***

ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: YES)

SOLUTION to ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: YES/NO) in MySql>

For solving this problem, when you try to login to root user, type

mysql -u root -p. You will be asked for password and enter correct password to login.

C:Program FilesMySQLMySQL Server 5.6bin>mysql -u root -p

Enter password: ****

Welcome to the MySQL monitor.  Commands end with ; or g.

Your MySQL connection id is 45

Server version: 5.6.25-log MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the current input statement.

mysql>

The default password  for user root is blank (i.e. an empty string). If in case it has never been changed then you may simply login to root user using mysql -u root command —

C:Program FilesMySQLMySQL Server 5.6bin>mysql -u root

Welcome to the MySQL monitor.  Commands end with ; or g.

Your MySQL connection id is 48

Server version: 5.6.25-log MySQL Community Server (GPL)

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its

affiliates. Other names may be trademarks of their respective

owners.

Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the current input statement.

mysql>

How to change the MySql user(root) password in MySql

Change MySql user password 1: Changing the root password — When root password is blank (i.e. an empty string).

you can use

SET PASSWORD FOR root@localhost = PASSWORD(‘new-password’);

to set new password.

C:Program FilesMySQLMySQL Server 5.6bin>mysql -u root

mysql> SET PASSWORD FOR root@localhost = PASSWORD(‘new-password’);

Query OK, 0 rows affected (0.00 sec)

mysql> SET PASSWORD FOR root@127.0.0.1 = PASSWORD(‘new-password’);

Query OK, 0 rows affected (0.00 sec)

mysql>

or, use

UPDATE mysql.user SET Password = PASSWORD(‘new-password’)

   WHERE User = ‘root’;

to set new password.

C:Program FilesMySQLMySQL Server 5.6bin>mysql -u root

mysql> UPDATE mysql.user SET Password = PASSWORD(‘new-password’)

   ->      WHERE User = ‘root’;

Query OK, 3 rows affected (0.00 sec)

Rows matched: 3  Changed: 3  Warnings: 0

mysql>

Change MySql user password 2: Changing the root password — When root password is NOT blank.

First you’ll have to enter existing password for root user, than you can use

SET PASSWORD FOR root@localhost = PASSWORD(‘new-password’);

to set new password.

C:Program FilesMySQLMySQL Server 5.6bin>mysql -u root -p

Enter password: ****

Welcome to the MySQL monitor.  Commands end with ; or g.

mysql> SET PASSWORD FOR root@localhost = PASSWORD(‘new-password’);

Query OK, 0 rows affected (0.00 sec)

mysql> SET PASSWORD FOR root@127.0.0.1 = PASSWORD(‘new-password’);

Query OK, 0 rows affected (0.00 sec)

mysql>

or,

use

UPDATE mysql.user SET Password = PASSWORD(‘new-password’)

   WHERE User = ‘root’;

to set new password.

C:Program FilesMySQLMySQL Server 5.6bin>mysql -u root -p

Enter password: ****

Welcome to the MySQL monitor.  Commands end with ; or g.

mysql> UPDATE mysql.user SET Password = PASSWORD(‘new-password’)

   ->      WHERE User = ‘root’;

Query OK, 3 rows affected (0.00 sec)

Rows matched: 3  Changed: 3  Warnings: 0

mysql>

Change MySql user password 3: Changing the root password using mysqladmin.

First you’ll have to enter existing password for root user, than you can enter set new password.

C:Program FilesMySQLMySQL Server 5.6bin>mysqladmin -u root -p password

Enter password: ****

New password: *****

Confirm new password: *****

C:Program FilesMySQLMySQL Server 5.6bin>

Change MySql user password 4: UBUNTU user can try this for setting up root password >

sudo dpkg-reconfigure mysql-server-5.6

In this MySql tutorial we solved very important MySql error —  How to resolve ERROR 1045 (28000): Access denied for user ‘root’@’localhost’ (using password: NO) /  (using password: YES) in MySql.

Related >>

How to change the MySql user(root) password tutorial

How to reset the forgotten MySql root password

How to fix Access denied for user root@localhost?

Yoodley is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

Have you recently been facing the error that says ‘Access denied for user ‘root’@’localhost’, whenever you try to operate MySQL?  In MySQL, the relational database management system, the error might show up when you attempt to access the root password. 

This post elucidates all possible solutions to help fix the error. However, it is equally important to understand what is causing the error ‘Access denied for user ‘root’@’localhost’ in the first place. 

Therefore, let us briefly understand what is causing MySQL to throw up the error ‘Access denied for user ‘root’@’localhost’, and then move on to solutions to fix the problem, followed by answering a few of the most asked questions relevant to the same.

Why does MYSQL say ‘Access denied for user ‘root’@’localhost’?

In all simplicity, you are facing the error ‘Access denied for user ‘root’@’localhost’ because as the root user, you do not have the adequate privilege (permission, in other terms) to access the MySQL database.

Now, to further the discussion, you could be facing the issue due to multiple reasons, some of which include:

  • When a user is non-existent to the MySQL server tries accessing the MySQL database.
  • When no privilege exists for the user (as mentioned).
  • If the user inputs the wrong username or password.

Now the error ‘Access denied for user ‘root’@’localhost’ is extensively of two types:

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

The former error message is thrown up when the root user tries to access the MySQL database with the password ‘yes’, which is wrong or different from the original password. Similarly, the latter error message occurs when the root user enters the password as ‘no’, which is incorrect.

Now that you know what could possibly be restraining you from accessing the database and throwing the message ‘Access denied for user ‘root’@’localhost’, below we look at X solutions to fix the same.

Solution:

In theory, it is the lack of permissions that throw the error ‘Access denied for user ‘root’@’localhost’. To provide all the permissions to the root user, you can use the ‘grant’ command to add privileges. Use the following chain of commands to grant privileges to the root user:

mysql> CREATE USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘password’;

        or

mysql> ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘password’;

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

mysql> FLUSH PRIVILEGES;

To take away the privileges and revert the changes, you can use the ‘revoke’ command. The ‘revoke’ command will do exactly what it sounds like: revoke all the privileges from the root user once you choose to remove the permissions/privileges.

Solution:

If your MySQL 5.7 (or higher version) is running in Ubuntu systems, the root user is to be authenticated using not the password but the auth_sccket plugin by default. 

Although this can come in handy and provide great usability and security, it can cause difficulty when you are trying to allow programs from the outside, such as phpMyAdmin, to access the user.

The main solution to this is to connect MySQL as root by switching authentication from auth_socket to mysql_native_password in the terminal:

sudo mysql

  • Run the ALTER USER command to configure the root account and change the authentication type to password.

ALTER USER ‘root’@’localhost’ IDENTIFIED WITH mysql_native_password BY ‘password’;

  • Now, run FLUSH PRIVILEGES; in the command prompt.
  • To confirm if the authentication configuration has been changed to a password, type the following command:

SELECT user,authentication_string,plugin,host FROM mysql.user;

  • Once confirmed, exit MySQL shell using 

exit

Solution:

This method works specifically for all macOS users. 

  • Firstly, install a version of MySQL that is compatible with your MacOS’s version.
  • Next, set the password for root during installation and note it down somewhere. Use the following command to set the root password:  

root <root-password>

  • Select Use Legacy Password Encryption from the two options available, the other one being Use Strong Password Encryption.
  • Using the search tool, open MySQL.prefPane and select the configuration tab.
  • Click ‘Select’ option of the ‘Configuration File’ and select /private/etc/my.cnf
  • Now, from the MySQL terminal, open a new file or an existing file, and type the following command:

 [mysqld]

 skip-grant-tables

With skipping the grant table, you can log in from anywhere and do almost anything on the database server.

  • Next, restart MySQL as follows:

ps aux | grep mysql

kill -9 <pid1> <pid2>

  • Upon restarting, run the following command to fix the error:

/usr/local/mysql-<version>-macos<version>-x86_64/bin/mysql -uroot -p<root-password>

Solution:

As we mentioned previously, you could be facing the error because you have been feeding the server the wrong password. Whether you don’t know the password or forgot the correct one, here is how you can reset it, so you can access the MySQL database as a root user again:

  • Open /etc/mysql/my.cnf from Configuration File. Now add ‘skip-grant-tables’ under [mysqld] section. Note that ‘skip-grant-tables’ is dangerous; therefore make sure to remove it towards the end of the solution.
  • Restart MySQL with the command given below:

service mysql restart

  • Since you have added the line of code ‘skip-grant-tables‘ already, you will be able to log in since MySQL will be skipping the grant-tables. Use the command below to log in:

mysql -u root

  • Once logged in, flush privileges that are restraining you from accessing the database originally using the command below:

mysql> flush privileges;

  • Now, set a new password using the command below:

Password=PASSWORD(‘my_password’) where USER=’root’;

FLUSH PRIVILEGES;

  • Since you have already reset the password, it is time to remove ‘skip-grant-tables’ from etc/mysql/my.cnf.
  • Restart MySQL again and log in using the new password. The service will no longer show the error.

FAQs

1. Where is the MYSQL error log?

Error logs are one of the most important logs in terms of IT operations because it helps in detecting and diagnosing functional problems that simply improves performance. 

The MYSQL error log basically contains error messages, warnings and different notes which are created during the startup and shutdown phases.

MYSQL error logging is always enabled and allows the users to set destination, verbosity levels and time zone. 

A file or the console is a general location or, say, destination of error logs. When no location is specified, then in windows, the error logs are written to host_name.err ( host_name is the host system name) in the data directory, whereas in UNIX/Linux, the console is the default destination of errors. 

A user can change the destination of error logs by specifying the location in the –log-error option (i.e., –log-error=”G:/TMP/mysql_logs/mysql_error.err” or –log-error=/var/log/mysql/error.log).

2. How to change the root password for MySQL?

To change the root password in MySQL:

  • In order to change the password for MYSQL, a new file must be created with the following contents – ALTER USER ‘root’@’localhost’ IDENTIFIED BY ‘PASSWORD’ ; (here password is the new password to be used) and this file should be saved as ~/mysql-pwd
  • Stop MYSQL with sudo systemctl stop mysql command and then issue the command: sudo mysqld -init-file=~/mysql-pwd. As the command prompt returns, restart the MYSQL using the sudo systemctl start mysql command. 
  • Now the MYSQL root user password is changed successfully, and you can login with the new admin password. 

3. How to recover the root password for MySQL?

To recover the root password in MySQL:

  • Use the sudo service mysql stop command to stop the MYSQL server.
  • Now start the MYSQL server using the sudo mysqld_safe –skip-grant-tables –skip-networking &
  • Use the mysql -u root command to connect to the MYSQL server as the root user.
  • Issue the following commands to reset the root password:

mysql> use mysql;

​mysql> update user set authentication_string=password(‘NEWPASSWORD’) where user=’root’;

​mysql> flush privileges;

​mysql> quit

Note: In the above commands, NEWPASSWORD is the new password to be used.

  • Restart the MYSQL daemon using sudo service mysql restart and log in with the new password. 

Понравилась статья? Поделить с друзьями:
  • Access based enumeration windows server 2016
  • Access 97 на windows 10 64 portable
  • Access 2020 скачать бесплатно для windows 10 на русском
  • Access 2019 скачать бесплатно для windows 10 на русском торрент
  • Access 2017 скачать бесплатно для windows 10 на русском