转载链接:https://www.cnblogs.com/zhengze/p/10702035.html
https://www.cnblogs.com/ryanzheng/p/9348723.html
本机环境

centos 7.2
mysql-5.7.9

一、修改密码

方法1: 用SET PASSWORD命令
首先登录MySQL。
格式:mysql> set password for 用户名@localhost = password('新密码');
例子:mysql> set password for root@localhost = password('123');

方法2:用mysqladmin
格式:mysqladmin -u用户名 -p旧密码 password 新密码
例子:mysqladmin -uroot -p123456 password 123

方法3:用UPDATE直接编辑user表
首先登录MySQL。
mysql> use mysql;
mysql> update user set password=password('123') where user='root' and host='localhost';
mysql> flush privileges;

二、忘记MySQL的root密码的解决方法

1、修改配置文件my.cnf

    在配置文件[mysqld]下添加skip-grant-tables,重启MySQL服务即可免密码登录

  其中--skip-grant-tables 选项前面曾经介绍过,意思是启动 MySQL 服务的时候跳过权限表认证。 启动后,连接到 MySQL 的 root 将不需要口令。

[mysqld]
skip-grant-tables

2、登录mysql

[root@localhost mysql]# mysql 
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 53
Server version: 5.7.9-community-log MySQL Community Edition (GPL)
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123';  
 ERROR 1290 (HY000): The MySQL server is running with the --skip-grant-tables option so it cannot execute this statement

mysql>use mysql;

mysql> update user set authentication_string = NULL where user = 'root';
Query OK, 1 row affected (0.00 sec)

3、还原my.cnf

到my.cnf 中删除skip-grant-tables选项,然后直接用mysql -uroot免密码登录后,在执行如下语句重设密码

mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123';