电脑环境
系统: Ubuntu 20.04 LTS
MySQL版本:8.0.23-0ubuntu0.20.04.1 (Ubuntu)
起因
由于最近刚从windows平台转来ubuntu平台进行使用,安装了数据库后,一直也没有去修改什么密码,用数据库都是在命令行上打上 sudo mysql -uroot -p
就直接使用了,但是在今天想着用Idea自带的database来操作数据库的时候,在test connection上显示 access denied,从之前的经验看,应该是我没有去初始化root的密码。
解决过程(可跳过)
我显示按照网上找的资料 Centos7如何修改或重置MySQL8.0 root密码 值得注意的是,我如果按照文中所说在/etc/my.cnf
最后一行添加 skip-grant-tables
的话,登录mysql会报一个error,经过查找资料得出得在/etc/mysql/mysql.conf.d/mysqld.cnf
下添加。
但是在执行完第三步把那一句注释掉后之后我发现我又连接不上mysql了
意味着我又要去把注释打开,可是打开了设置密码时会发生如下问题
这就好像是一个死循环。
最终解决
在查阅了很多资料后,找到一个可行的办法,也不用去改什么配置文件:
-
使用系统 root 权限进入mysql
sudo mysql -u root -p
-
直接用以下 SQL 设置密码
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'new-password';
-
如果提示密码不符合标准则执行以下:
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> set global validate_password.policy=0; Query OK, 0 rows affected (0.00 sec) mysql> set global validate_password.length=1; Query OK, 0 rows affected (0.00 sec)
-
再次修改后,重启服务即可
mysql> ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '123456'; Query OK, 0 rows affected (0.02 sec) mysql> quit; Bye airili@airili-Lenovo:~$ sudo service mysql stop airili@airili-Lenovo:~$ sudo service mysql start airili@airili-Lenovo:~$ mysql -uroot -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 8 Server version: 8.0.23-0ubuntu0.20.04.1 (Ubuntu) Copyright (c) 2000, 2021, Oracle and/or its affiliates. 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>