MySQL 錯誤 ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'python' 通常因匿名用戶或權限設定不當導致。本文整理多種修復方案,從簡單的 Root 登入到跳過權限表的深度修復。
嘗試建立資料庫時出現:
mysql> CREATE DATABASE python; ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'python'
關鍵線索:user ''@'localhost' 顯示為空用戶名,實為匿名帳戶登入。
mysql --user=root -p
輸入 Root 密碼後即擁有完整權限:
mysql> create database python; Query OK, 1 row affected (0.00 sec) mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | python | | test | +--------------------+
MySQL user 表中存在 User='' 的匿名帳戶,導致即使指定 -u root 仍被視為匿名登入。
my.ini (Windows) 或 my.cnf (Linux),在 [mysqld] 區段加入:skip-grant-tablesmysql> use mysql;
mysql> update user set password=password('新密碼') WHERE User='root';
mysql> flush privileges;
skip-grant-tables 並重啟服務# 停止服務 service mysqld stop # 以跳過權限模式啟動 mysqld_safe --user=mysql --skip-grant-tables --skip-networking & # 新開終端免密登入 mysql -u root -p -hlocalhost # 修復權限 (見方案一 SQL 指令)
service mysqld stop mysqld_safe --user=mysql --skip-grant-tables --skip-networking & mysql -u root -p -hlocalhost # 進入 MySQL 後執行: use mysql; SELECT host,user,password,Grant_priv,Super_priv FROM mysql.user; UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root'; FLUSH PRIVILEGES; GRANT ALL ON *.* TO 'root'@'localhost'; GRANT ALL ON *.* TO 'root'@'127.0.0.1'; FLUSH PRIVILEGES; quit service mysqld start
mysql_secure_installation 移除匿名用戶mysql.user 表確認無異常帳戶