安装教程参考:
https://blog.csdn.net/weixin_39823200/article/details/113546725
工具:
mysql Ver 14.14 Distrib 5.7.25, for Linux (x86_64)
问题描述:
Ubuntu在安装完成mysql后,无法直接通过mysql -u root -p命令登录mysql,出现如下错误:ERROR 1698 (28000): Access denied for user ‘root’@‘localhost’
解决方法:
Ubuntu linux下安装新版本mysql,安装时root密码是随机的,因此会出现上述错误。
第一步,登录mysql
既然我们无法通过root用户进入MySQL,那我们就只能通过其他用户登录MySQL了。在我们下载安装MySQL的时候系统给我们创建了一个用户。打开 /etc/mysql/debian.cnf如下。
book@100ask:~$ sudo cat /etc/mysql/debian.cnf
book@100ask:~$ sudo cat /etc/mysql/debian.cnf
# Automatically generated for Debian scripts. DO NOT TOUCH!
[client]
host = localhost
user = debian-sys-maint
password = 0NBFUVaaRF8KiZBD
socket = /var/run/mysqld/mysqld.sock
[mysql_upgrade]
host = localhost
user = debian-sys-maint
password = 0NBFUVaaRF8KiZBD
socket = /var/run/mysqld/mysqld.sock
我们找到client的user和password,然后在终端输入
mysql -u debian-sys-maint -p
然后回车输入 password的内容。这样就进入了MySQL了,如图:
book@100ask:~$ mysql -u debian-sys-maint -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 3
Server version: 5.7.38-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2022, 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.
第二步,查看user表
在mysql中输入:
select user, plugin from mysql.user;
结果如下:
+------------------+-----------------------+
| user | plugin |
+------------------+-----------------------+
| root | auth_socket |
| mysql.session | mysql_native_password |
| mysql.sys | mysql_native_password |
| debian-sys-maint | mysql_native_password |
+------------------+-----------------------+
4 rows in set (0.00 sec)
第三步,修改root密码
输入以下命令,其中123456是密码:
update mysql.user set authentication_string=PASSWORD('123456'), plugin='mysql_native_password' where user='root';
mysql> update mysql.user set authentication_string=PASSWORD('123456'), plugin='mysql_native_password' where user='root';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 1
第四步,刷新
输入以下命令:
flush privileges;
然后重新启动服务器,就可以正常登录啦
sudo service mysql restart