MySQL 8.x 修改root用户密码/修改密码/重置密码/忘记密码(为了避免掉坑,值得收藏)

操作系统:CentOS Linux release 8.2.2004 (Core)
MySQL版本:mysql Ver 8.0.26 for Linux on x86_64 (Source distribution)

忘记 root 用户的密码,然后我以无需“权限验证”的方式启动 MySQL 服务器(具体方法参考这里),接着我登录 MySQL,然后输入下面的命令修改 root 用户的密码:

update user set authentication_string=password('123456') where user='root';
# 或者
set password for 'root'@'localhost' = password('123456');

结果报错:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('123456') WHERE User='root'' at line 1

报错原因:MySQL 8.0 不支持 password() 函数。

在 MySQL 8.0 中正确的修改用户密码的命令如下:

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

或者

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

结果还是报错:

ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement

原因:你没有刷新权限,你需要执行 flush privileges 就不会报错了。

接着继续执行修改密码的命令,又报错了:

ERROR 1396 (HY000): Operation ALTER USER failed for 'root'@'localhost'

解决办法:
mysql.user 表中删除用户 root@localhost,然后刷新权限 FLUSH PRIVILEGES,再新建用户 root@localhost 就不会有这个问题了。

删除用户、创建用户的命令:

delete from user where user='root' and host='localhost';
# 刷新权限
flush privileges;
# 创建用户
create user 'root'@'localhost' identified by '123456';
# 给用户授权
GRANT ALL PRIVILEGES ON *.* TO 'root'@localhost WITH GRANT OPTION;

你也可以使用 drop 语句删除用户,该语句有个好处,会自动刷新权限,所以删除后,可以直接创建用户。

drop user 'root'@'localhost';

纠正下:
修改用户密码,没有必要先删除用户再创建用户。其实在 MySQL 8.x 中无法直接修改用户的密码是因为字段 authentication_string 有值,所以无法直接修改,我们可以先将要修改密码的用户的字段 authentication_string 置为空,再设置新的密码,没有必要删除该用户。

update user set authentication_string='' where user='root';--将字段authentication_string置为空
ALTER user 'root'@'localhost' IDENTIFIED BY '123456';--修改密码为123456

猜你喜欢

转载自blog.csdn.net/liaowenxiong/article/details/123216004#comments_22386996
今日推荐