從供應商那邊接手一個MySQL數據庫(數據庫版本為5.7.21 MySQL Community Server (GPL)),在創建賬號時遇到了“ERROR 1044 (42000): Access denied for user 'root'@'localhost' to database xxx”錯誤,如下所示
mysql> grant all on xxx.* to xxx@'192.168.%' identified by 'xxx';
ERROR 1044 (42000): Access denied for user 'root'@'localhost' to database 'xxxx'
mysql>
照理說,root用戶應該有任何權限,那么為什么出現這個錯誤呢? 查看當前用戶為root@localhost,順便查看了一下各個root賬號的權限。如下所示:
mysql> select current_user() from dual;
+----------------+
| current_user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec
mysql> select host,user from user where user='root';
+-----------+----------+
| host | user |
+-----------+----------+
| % | root |
| 127.0.0.1 | root |
| ::1 | root |
| localhost | root |
+-----------+----------+
7 rows in set (0.00 sec)
mysql> show grants for root@'localhost';
+--------------------------------------------------------------+
| Grants for root@localhost |
+--------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' |
| GRANT PROXY ON ''@'' TO 'root'@'localhost' WITH GRANT OPTION |
+--------------------------------------------------------------+
2 rows in set (0.00 sec)
mysql> show grants for root@'127.0.0.1';
+---------------------------------------------------------------------+
| Grants for root@127.0.0.1 |
+---------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'127.0.0.1' WITH GRANT OPTION |
+---------------------------------------------------------------------+
1 row in set (0.00 sec)
mysql> show grants for root@'%';
+-------------------------------------------+
| Grants for root@% |
+-------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' |
+-------------------------------------------+
1 row in set (0.00 sec)
如上所示,root@localhost賬號沒有WITH GRANT OPTION選項,關於WITH GRANT OPTION選項,如果想讓授權的用戶,也可以將這些權限授予給其他用戶,需要選項 “WITH GRANT OPTION“ 。也就是說有這個選項就可以將權限傳遞給第三方。這也是上面root@localhost用戶給其它用后授權報錯的原因,如果以 root@127.0.0.1登錄(此賬號擁有WITHGRANT OPTION選項),創建用戶並授權就不會有這個錯誤,如下所示:
# mysql -host 127.0.0.1 -u root -p
Enter password:
mysql> grant all on xxx.* to xxx@'192.168.%' identified by 'test1249';
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
當然還有其它方面的原因也可能會引起這個錯誤,不過在這個案例當中,確實僅僅是因為上面原因引起。特此記錄一下這個案例@!