如何在 MySQL 中以 root 身份登录?

Sag*_*Das 5 mysql login phpmyadmin

我已经安装了 MySQL,在安装过程中我被要求输入密码,但现在我的老师说我们应该能够在没有任何密码的情况下以 root 身份登录。

这有效,但我没有任何特权:

登录提示用户名 phpmyadmin

这不起作用:

登录提示用户名root,密码已输入,无法访问

这也不行

登录提示,用户名 root,无密码,无访问权限

Ser*_*nyy 14

问题原因

rootMySQL 5.7中以用户身份登录的默认配置需要使用身份验证套接字。这可以通过查询user表来验证:

mysql> select user,authentication_string,plugin from user where user='root';
+------+-----------------------+-------------+
| user | authentication_string | plugin      |
+------+-----------------------+-------------+
| root |                       | auth_socket |
+------+-----------------------+-------------+
1 row in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)

文档

socket插件检查socket用户名(操作系统用户名)是否与客户端程序向服务器指定的MySQL用户名匹配。如果名称不匹配,插件会检查套接字用户名是否与 mysql.user 系统表行的 authentication_string 列中指定的名称匹配。如果找到匹配项,则插件允许连接。

换句话说,mysql 默认没有设置 root 密码 - 您需要以 root 身份或通过运行 phpMyAdmin sudo(出于安全原因,这两个都是坏主意),或者更改身份验证方法并重置 root 密码,如图所示在数字海洋教程中

请注意,除了名称相同之外,MySQL 用户和系统用户并不相同。您可以有一个 MySQL 用户jdoe,但主机系统上没有这样的用户。因此,root是 MySQL 的 root 用户,而不是系统用户。

更改插件和密码的步骤:

  1. 打开终端并运行sudo mysql -u root。您应该会看到一条问候消息和mysql>提示。这是 MySQL shell,它不同于你的命令行 shell,所以这里只接受 SQL 语句。

  2. 输入以下 SQL 查询序列:

    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> flush privileges;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql>  UPDATE user SET plugin='mysql_native_password',authentication_string=PASSWORD('newpassword') WHERE user = 'root';
    Query OK, 1 row affected, 1 warning (0.00 sec)
    Rows matched: 1  Changed: 1  Warnings: 1
    
    Run Code Online (Sandbox Code Playgroud)
  3. 退出并尝试登录:

    mysql> exit
    Bye
    
    $ sudo systemctl restart mysql
    $ sudo mysql -u root -p
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 5
    Server version: 5.7.21-1 (Debian)
    
    Copyright (c) 2000, 2018, 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> 
    
    Run Code Online (Sandbox Code Playgroud)

如果一切顺利,您应该可以通过新密码从 phpMyAdmin 登录。如果出现问题,请尝试在没有权限检查的情况下重新启动服务器(这是 Digital Ocean 教程中的第 3 步)。对于其他问题,请随时在此处或在数据库管理员上提出另一个问题

  • Sergiy Kolodyazhnyy 的回答对我有用,但最后我不得不重新启动( systemctl restart mysql ) (3认同)
  • @SagnikDas 命令是“sudo mysql -u root”。您使用了不完整的“sudo mysql”。 (2认同)