'user'@'localhost' 的访问被拒绝

Access denied for 'user'@'localhost'

我正在尝试使用 phalcon 创建模型。但是当我输入 phalcon model polls 时,我得到一个错误 ERROR: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES)

我可以使用 mysql -p 进入 mysql。所以我试图创建新用户并授予他所有权限,但没有帮助。我也可以使用 root 和密码登录到 phpmyadmin。我也尝试在配置文件中将端口指定为 3306,但仍然没有。

我的配置文件:

defined('BASE_PATH') || define('BASE_PATH', getenv('BASE_PATH') ?: realpath(dirname(__FILE__) . '/../..'));
defined('APP_PATH') || define('APP_PATH', BASE_PATH . '/app');

return new \Phalcon\Config([
    'database' => [
        'adapter' => 'Mysql',
        'host' => 'localhost',
        'port' => 3306,
        'username' => 'root',
        'password' => '$Pass1234 ',
        'dbname' => 'poll_db',
        'charset' => 'utf8',
    ],
    'application' => [
        'appDir' => APP_PATH . '/',
        'controllersDir' => APP_PATH . '/controllers/',
        'modelsDir' => APP_PATH . '/models/',
        'migrationsDir' => APP_PATH . '/migrations/',
        'viewsDir' => APP_PATH . '/views/',
        'pluginsDir' => APP_PATH . '/plugins/',
        'libraryDir' => APP_PATH . '/library/',
        'cacheDir' => BASE_PATH . '/cache/',

        // This allows the baseUri to be understand project paths that are not in the root directory
        // of the webpspace.  This will break if the public/index.php entry point is moved or
        // possibly if the web server rewrite rules are changed. This can also be set to a static path.
        'baseUri' => preg_replace('/public([\/\\])index.php$/', '', $_SERVER["PHP_SELF"]),
    ]
]);

P.S 我通过 mysql -u root -p

完成了所有关于授予进入 mysql 权限的操作

P.P.S 我也做了 FLUSH PRIVILEGES 然后重启了 mysql,但是没有。感谢您以后的帮助。

UPD:我还尝试在 laravel 中创建项目,并进行迁移,一切正常。我也是用root+password.

已解决:我不知道为什么,但我决定创建一个新项目,即使使用 'root'@'localhost',一切都运行良好。似乎第一个项目出了点问题。尽管如此,感谢所有参与帮助的人。

P.S 我将 EternHour's 答案标记为解决方案,仅供将来可能遇到相同错误的人使用。

我认为这不是端口问题,请求正在到达目的地。当通过命令行 (mysql -u root -p) 登录时,使用 root@localhost 将起作用,但您不想使用它来连接您的代码。请记住,在建立连接时,您需要明确使用 host=localhosthost=127.0.0.1。如果您使用 IP 地址(即使在同一台服务器上),您将被拒绝访问。

[user@localhost ~]# mysql --host=127.0.0.1 --protocol=TCP -u root -p
Enter password:
mysql>
[user@localhost ~]# mysql --host=192.168.1.10 --protocol=TCP -u root -p
Enter password:
ERROR 1045 (28000): Access denied for user 'root'@'hostname' (using password: YES)

以下是我建议采取的步骤:

  1. 创建可用于在脚本中进行连接的专用用户。
  2. 如果脚本源与 MySQL 相同的服务器。

    CREATE USER '<user>'@'localhost'
    IDENTIFIED BY 'password';
    GRANT ALL
    ON <database>.*
    TO '<user>'@'localhost';
    
  3. 如果连接总是从与 MySQL 相同但不同的位置建立,运行 命令行上的以下内容。

    CREATE USER '<user>'@'<IP_address>'
    IDENTIFIED BY 'password';
    GRANT ALL
    ON <database>.*
    TO '<user>'@'<IP_address>';
    
  4. 如果连接源不同,运行以下命令。

    CREATE USER '<user>'@'<IP_address>'
    IDENTIFIED BY 'password';
    GRANT ALL
    ON <database>.*
    TO '<user>'@'%';
    

如果您有任何问题,这里是 link documentation