ITPub博客

首页 > 数据库 > MySQL > MySQL 忘记root密码的两种解决方法

MySQL 忘记root密码的两种解决方法

原创 MySQL 作者:T1YSL 时间:2025-08-13 17:12:42 0 删除 编辑

1.skip-grant-tables

2.init-file


启动mysqld的时候加上参数skip-grant-tables

在默认的参数文件中加上 skip-grant-tables

root@infokist:/etc/mysql# service mysql restart

root@infokist:/etc/mysql# mysql

mysql> update mysql.user set authentication_string=password('dingjia') 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.01 sec)


MySQL 8 中的变化

加了 skip-grant-tables 参数后会自动加上 skip-networking 不允许远程连接

移除了 PASSWORD() 函数

修改密码的方法是用 alter user 的命令修改密码,但注意要载入权限表后才能 alter user

mysql> alter user root identified by 'dingjia';

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

mysql> flush privileges;

Query OK, 0 rows affected (0.07 sec)

mysql> alter user root@localhost identified by 'dingjia';

Query OK, 0 rows affected (0.02 sec)、



init-file方案

使用 –init-file 参数启动实例,类似: mysqld_safe --init-file=/tmp/chpw.sql &

在 chpw.sql 文件里面写上密码修改语句:

alter user 'root'@'localhost' identified by 'dingjia';


实例启动成功后,密码即修改完毕

这种方法只会重启一次 MySQL 实例,而且基本上不存在安全隐患





来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69990629/viewspace-3093385/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
中国开源软件推进联盟PG分会系列技术丛书《快速掌握PostgreSQL版本新特性》一书副主编。数据库技术专家。数据库认证讲师、恩墨学院数据库讲师。擅长MySQL数据库、PostgreSQL等开源数据库。拥有MySQL-OCP 、PostgreSQL-PGCM等数据库认证。

注册时间:2020-12-12

  • 博文量
    152
  • 访问量
    160743