MySQL无法登录问题-"ERROR 1045 (28000): Access denied for user 'root'@'localhost'"-之解决方法-密码重置

笔者在CentOS7上安装MySQL 5.7版本,安装完成后,登录的时候,提示登录被拒绝:

[root@cdh1 ~]# mysql -uroot -p
Enter password: 
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

以前安装5.6版本的时候,root用户的默认密码为空, 提示输入密码时,敲回车即能登录。但是此次安装的5.7版本按默认密码为空的方式登录,却不能登录。原因是5.7版本中,系统会随机为root用户设置一个密码。此时,若想进入mysql命令行模式,需先进行root用户的密码重置操作。

root用户密码重置非常简单:

1、修改文件:/etc/my.cnf :

 找到 mysql配置的代码块,添加一行配置 skip-grant-tables , 绕过密码验证,如下图:


修改完,保存退出,并重启mysql

[root@cdh1 etc]# systemctl restart mysqld.service

2、进入mysql命令行, 修改root用户的密码:

[root@cdh1 etc]# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.21 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, 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> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed

mysql> update user set authentication_string = password('123'), password_expired = 'N', password_last_changed = now() where user = 'root';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

mysql> quit;
Bye

此处需要注意,在5.6版本中,密码字段是 password , 在5.7版本中,密码字段是 authentication_string 。

3、将/etc/my.cnf 文件恢复原状,即删除第一步中添加的配置:skip-grant-tables , 保存退出。

4、重启mysql服务,即可使用新密码进行登录:

[root@cdh1 etc]# systemctl restart mysqld.service
[root@cdh1 etc]# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.21 MySQL Community Server (GPL)

Copyright (c) 2000, 2018, 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>
至此,MySQL 的root用户默认密码修改完成!
发布了27 篇原创文章 · 获赞 43 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/u010476994/article/details/79351128