如果不幸忘记或丢失了 MySQL root用户的密码,需要一种方法来以某种方式恢复它。 我们需要知道的是密码存储在用户表中。 这意味着我们需要想办法绕过 MySQL 认证,这样我们才能更新密码记录。 幸运的是,有一个简单的实现,本教程将指导您完成在 MySQL 8.0 版本中恢复或重置 root 用户密码的过程。 根据 MySQL 文档,有两种方法可以重置root用户的密码。其中一种方法是使用 --skip-grant-tables 选项启动 MySQL 服务。 这不太安全,因为当服务以这种方式启动时,所有用户都可以在没有密码的情况下进行连接,不过这种方法比较简单,我们首先来看看这种方法。测试环境 操作系统:Rocky Linux 8.5 (Green Obsidian) MySQL:Ver 8.0.26 for Linux on x86_64 (Source distribution) 如果服务器启动--skip-grant-tables,--skip-networking 选项会自动激活,因此远程连接将不可用。重置root密码步骤 首先停止MySQL服务# systemctl stop mysqld.service # for distros using systemd # /etc/init.d/mysqld stop # for distros using init 使用 选项 --skip-grant-tables 启动MySQL服务# mysqld --skip-grant-tables --user=mysql & [1] 321135 然后,您只需运行mysq即可连接到mysql服务器。# mysql Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 7 Server version: 8.0.26 Source distribution Copyright (c) 2000, 2021, Oracle and/or its affiliates. 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. 由于使用 --skip-grant-tables 选项启动服务时禁用了帐户管理,因此我们将不得不重新加载授权。 这样我们以后就可以更改密码:mysql> FLUSH PRIVILEGES; Query OK, 0 rows affected (0.07 sec) mysql> quit; Bye 现在可以运行以下查询来更新密码。 确保将"new_password"更改为您希望使用的实际密码。mysql> ALTER USER "root"@"localhost" IDENTIFIED BY "new_passowrd"; Query OK, 0 rows affected (0.00 sec) 现在停止 MySQL 服务器,然后正常启动它。# systemctl stop mysqld.service # for distros using systemd # systemctl restart mysqld.service # for distros using systemd # /etc/init.d/mysqld stop # for distros using init # /etc/init.d/mysqld restart # for distros using init 现在使用新密码再次连接MySQL# mysql -u root -p Enter password: Welcome to the MySQL monitor. Commands end with ; or g. Your MySQL connection id is 8 Server version: 8.0.26 Source distribution Copyright (c) 2000, 2021, Oracle and/or its affiliates. 小插曲 启动mysqld时,如果遇到下面的错误[MY-012574] [InnoDB] Unable to lock ./ibdata1 error: 11 搜索一番,参考文章2和3给出了各种可能性,通过查询可以看出确实有个mysqld服务未关闭,可是之前我确实关闭了mysql,不知道怎么回事。# ps aux| grep mysql mysql 321135 0.5 12.0 2141572 349256 pts/0 Sl 01:54 0:09 mysqld --skip-grant-tables --user=mysql 只能通过kill命令杀死mysql# kill 321135参考https://www.tecmint.com/reset-root-password-in-mysql-8/https://bobcares.com/blog/innodb-unable-to-lock-ibdata1-error-11/https://bobcares.com/blog/innodb-unable-to-lock-ibdata1-error-11/