修改MySql密码
背景
在Linux系统中使用MySql数据库时,若忘记登录密码,如下

则可以按以下步骤进行更改密码:
(注:因为作者是在服务器里用的 Linux,故在虚拟机或者其他平台上不保证下面的步骤可以实现!)
1、检查 MySql 状态
检查本机 MySql 的启动状态,若启动则将其进行关闭,如下
[root@VM-0-8-centos ~]# ps -aux | grep -i mysql
mysql 1225 0.0 0.0 113420 1596 ? Ss Jan08 0:00 /bin/sh /usr/bin/mysqld_safe --basedir=/usr
mysql 1462 0.0 4.4 1119992 84320 ? Sl Jan08 1:28 /usr/libexec/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib64/mysql/plugin --log-error=/var/log/mariadb/mariadb.log --pid-file=/var/run/mariadb/mariadb.pid --socket=/var/lib/mysql/mysql.sock
root 21395 0.0 0.0 112812 992 pts/6 R+ 16:17 0:00 grep --color=auto -i mysql
[root@VM-0-8-centos ~]#
如图,其中 mysql 并非处于运行态,若显示正在运行,则可利用下述代码进行关闭
[root@VM-0-8-centos ~]# service mysql stop
[root@VM-0-8-centos ~]#
2、修改 MySql 配置文件
修改MySql 的配置文件 my.cnf ,其位置一般在 /etc/my.cnf,有些版本在 /etc/mysql/my.cnf。具体如下
2.1 进入配置文件
[root@VM-0-8-centos ~]#
[root@VM-0-8-centos ~]# vi /etc/my.cnf
2.2 添加代码 skip-grant-tables ,如下

其作用是登录 mysql 时,直接跳过密码!
之后启动 mysql 服务,并进入 mysql,即
[root@VM-0-8-centos ~]# service mysqld start
[root@VM-0-8-centos ~]# mysql -u root
3、修改登陆密码
进入数据库后,需要修改登陆密码,整体操作如下
MariaDB [(none)]> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
之后输入
update mysql.user set authentication_string=password('新密码') where user='root';
其中,括号中的 新密码 ,便是自己设置的密码。
然后再输入
MariaDB [mysql]> flush privileges;
Query OK, 0 rows affected (0.00 sec)
上述语句主要是用于刷新mysql的系统权限相关表。
最后退出mysql
MariaDB [mysql]> exit
Bye
4、重启 MySql
首先删除掉 2.2 中为 /etc/my.cnf 文件添加的语句,然后重启 mysql ,再输入密码就可进入mysql中了。具体如下
[root@VM-0-8-centos ~]# service mysqld start
[root@VM-0-8-centos ~]# mysql -u root -p
Enter password:
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MariaDB connection id is 85
Server version: 5.5.68-MariaDB MariaDB Server
以上即为在 Linux 中忘记 MySQL 登陆密码后修改密码的处理方法!
侵权删~










