部分内容来自以下博客:
https://www.cnblogs.com/wuotto/p/9682400.html
1 关闭MySQL数据库
使用命令检查MySQL数据库是否已经关闭:
[root@localhost ~]# systemctl status mysql
出现“Active: inactive (dead)”表示数据库已关闭,如果是“Active: active (exited)”表示已开启,需要手动关闭:
[root@localhost ~]# systemctl stop mysql
2 修改MySQL的配置文件
找到MySQL的配置文件“my.cnf”,默认路径是:“/etc/my.cnf”。
打开文件并在“[mysqld]”下添加:
skip-grant-tables
这句话的作用是在登录MySQL的时候可以跳过密码直接登录。
保存修改并退出。
3 启动MySQL
使用命令启动MySQL:
[root@localhost ~]# systemctl start mysql
输入“mysql”即可进入数据库。
4 修改密码
连接“mysql”数据库,修改用户密码:
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> update mysql.user set password=password('123456') where user='root';
Query OK, 5 rows affected (0.00 sec)
Rows matched: 5 Changed: 5 Warnings: 0
mysql>
将root用户的密码设为123456。
刷新使改动生效:
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
5 回改文件并重启
退出MySQL,重新打开“my.cnf”配置文件,删除“skip-grant-tables”,保存退出。
重启MySQL,需要密码登录,输入设置的密码即可:
[root@localhost ~]# vim /etc/my.cnf
[root@localhost ~]# systemctl restart mysql
[root@localhost ~]# mysql
ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)
[root@localhost ~]# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.6.45 MySQL Community Server (GPL)
Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.
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>