1.如果記得原密碼,以原密碼登錄MySQL。否則需要先修改my.cnf文件,在mysqld模塊中增加一行:skip-grant-tables,然後重啓mysqld,並以空密碼登錄(直接回車)。
$ mysql -uroot -p
Enter password:
2.修改密碼。
mysql> alter user root@'%' identified by [with mysql_native_password] 'Admin123!@#';
Query OK, 0 rows affected (0.02 sec)】
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
注意,這裏可能需要一個高強度的密碼,MySQL8默認的驗證密碼強度(validate_password_policy)爲"MEDIUM",可通過下面語句查詢當前密碼強度:
mysql> show variables like "%validate_password%";
+--------------------------------------+--------+
| Variable_name | Value |
+--------------------------------------+--------+
| validate_password_check_user_name | ON |
| validate_password_dictionary_file | |
| validate_password_length | 8 |
| validate_password_mixed_case_count | 1 |
| validate_password_number_count | 1 |
| validate_password_policy | MEDIUM |
| validate_password_special_char_count | 1 |
+--------------------------------------+--------+
7 rows in set (0.11 sec)
// 如果要修改密碼強度,可以執行下面語句
mysql> set global validate_password_policy=LOW;
Query OK, 0 rows affected (0.03 sec)
若以上不起作用,則可以先刪除root用戶,再新增root用戶。
mysql> 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
Database changed
mysql> delete from user where user='root';
Query OK, 1 row affected (0.02 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
mysql> create user 'root'@'%' identified by 'Admin123!@#';
Query OK, 0 rows affected (0.01 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> grant all privileges on *.* to root@'%';
Query OK, 0 rows affected (0.01 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
然後重啓mysqld,用root用戶的新密碼登錄即可。