從供應商那邊接手一個MySQL數據庫(數據庫版本爲5.7.21 MySQL Community Server (GPL)),在建立帳號時遇到了「ERROR 1044 (42000): Access denied for user 'root'@'localhost' to database xxx」錯誤,以下所示html
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
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選項),建立用戶並受權就不會有這個錯誤,以下所示:sql
# 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)
固然還有其它方面的緣由也可能會引發這個錯誤,不過在這個案例當中,確實僅僅是由於上面緣由引發。特此記錄一下這個案例@!數據庫