MySQL Q&A - [01] root密码忘记了怎么办

题记部分

 

 

Windows 场景下

 

1、先使用管理员身份打开两个命令提示符窗口(winA和winB)

2、在命令提示符窗口winA中将MySQL服务停掉net stop mysql

Microsoft Windows [版本 10.0.22621.1413]
(c) Microsoft Corporation。保留所有权利。

C:\Windows\System32>net stop mysql
MySQL 服务正在停止.
MySQL 服务已成功停止。

3、输入mysqld --console --skip-grant-tables --shared-memory

Microsoft Windows [版本 10.0.22621.1413]
(c) Microsoft Corporation。保留所有权利。

C:\Windows\System32>net stop mysql
MySQL 服务正在停止.
MySQL 服务已成功停止。

C:\Windows\System32>mysqld --console --skip-grant-tables --shared-memory
2023-03-30T06:09:38.525723Z 0 [System] [MY-010116] [Server] D:\Plugins\mysql\bin\mysqld.exe (mysqld 8.0.28) starting as process 21596
2023-03-30T06:09:38.545438Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
2023-03-30T06:09:38.776569Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
2023-03-30T06:09:38.911341Z 0 [Warning] [MY-011311] [Server] Plugin mysqlx reported: 'All I/O interfaces are disabled, X Protocol won't be accessible'
2023-03-30T06:09:38.964124Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
2023-03-30T06:09:38.964391Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
2023-03-30T06:09:39.003842Z 0 [System] [MY-010931] [Server] D:\Plugins\mysql\bin\mysqld.exe: ready for connections. Version: '8.0.28'  socket: ''  port: 0  MySQL Community Server - GPL.

4、在命令提示符窗口winB中登录MySQLmysql -uroot -p (在Enter password:处直接按回车键即可)

C:\Windows\System32>mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 7
Server version: 8.0.28 MySQL Community Server - GPL

Copyright (c) 2000, 2022, 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.

mysql>

5、切换到数据库mysql:use mysql;

6、修改root用户密码:alter user root@localhost identified by '新密码';

7、刷新权限表:flush privileges;

8、退出之后将两个窗口关掉,然后启动MySQL服务,用新密码登录即可。

 

 

Linux 场景下

1、修改MySQL的配置文件(默认为/etc/my.cnf),在[mysqld]段下添加一行skip-grant-tables。

2、保存配置文件后,重启MySQL服务。可以使用以下命令重启MySQL服务:service mysqld restart

3、再次进入MySQL命令行,使用以下命令登录MySQL数据库:mysql -u root -p 输入密码时直接回车,就会进入MySQL数据库。

4、按照常规流程修改root密码。可以使用以下命令来修改密码:

use mysql;
update user set password=password('新密码') where user='root';
flush privileges;

5、密码修改完毕后,再按照步骤1中的流程,删掉配置文件中的那行skip-grant-tables,并且重启MySQL服务,新密码就生效了。可以使用以下命令重启MySQL服务:service mysqld restart


注意事项

  • 在重置root密码的过程中,需要确保服务器处于安全的状态,即没有人能够任意地连接MySQL数据库。可以采用将MySQL对外的端口封闭,并且停止Apache以及所有的用户进程的方法实现服务器的准安全状态。最安全的状态是到服务器的Console上面操作,并且拔掉网线。
  • 在修改root密码时,请确保使用强密码,并妥善保管新密码。

 

 

 

 

— 业精于勤荒于嬉,行成于思毁于随 —

posted @ 2023-06-09 10:42  HOUHUILIN  阅读(427)  评论(0编辑  收藏  举报