在数据库管理的过程中,我们时常会遭遇一些意想不到的困境。其中,MySQL root密码的遗忘无疑是最为棘手的问题之一。密码一旦丢失,就意味着管理员无法正常登录数据库服务器,更无法进行数据的查询、修改和管理。面对这样的困境,我们该如何解决呢?本文将为您详细解析MySQL忘记root密码的应对之道。
MySQL忘记root密码解决方案
如果你忘记了 MySQL root 密码,有俩种重置密码的方式。
第一种使用 --skip-grant-tables 选项启动数据库
使用这种方式的话,先要停止 MySQL 实例,然后启动的时候带上--skip-grant-tables 选项,这样的话, MySQL 不会加载授权表的数据。
停止数据库服务器的运行:
systemctl stop mysql
使用 --skip-grant-tables 选项启动数据库:
sudo -u mysql /usr/local/mysql/bin/mysqld --daemonize --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --user=mysql --log-error=iZuf64k4o0v3oct9e0yh8wZ.err --pid-file=/usr/local/mysql/data/iZuf64k4o0v3oct9e0yh8wZ.pid --skip-grant-tables

无密码 使用root 登陆
mysql -u root
如果遇到下面错误,请执行:

apt-get install libncurses*
mysql: error while loading shared libraries: libtinfo.so.5: cannot open shared object file: No such
执行flush privileges 重新加载授权,并且更改密码
flush privileges;
alter user 'root'@'localhost' IDENTIFIED BY 'rootpass';

使用新密码登陆
mysql -u root -prootpass

重启数据库

第二种使用 --init-file 选项启动数据库
可以在 某个文件中保存修改root用户密码的 SQL,然后数据库启动的加上 --init-file=fileName , MySQL 在启动的时执行 fileName 文件的内容,更改 root 用户的密码。停止数据库服务器的运行:
systemctl stop mysql
在mysql 数据目录创建初始化文件,
vim /usr/local/mysql/data/pass-file
保存修改密码SQL到文件 pass-file
alter user 'root'@'localhost' IDENTIFIED BY 'rootpass2';
使用 --init-file 选项启动数据库
sudo -u mysql /usr/local/mysql/bin/mysqld --daemonize --basedir=/usr/local/mysql --datadir=/usr/local/mysql/data --user=mysql --log-error=iZuf64k4o0v3oct9e0yh8wZ.err --pid-file=/usr/local/mysql/data/iZuf64k4o0v3oct9e0yh8wZ.pid --init-file=/usr/local/mysql/data/pass-file
使用 rootpass2密码登陆
/usr/local/mysql/bin/mysql -u root -prootpass2

忘记MySQL root密码是一个常见但棘手的问题。通过以上方法,我们可以有效地解决这个问题。此外,为了防止密码遗忘的情况发生,建议定期更换密码并使用强密码策略,同时确保备份的及时性和安全性。
评论