MySQL在grant時報錯ERROR 1064 (42000)的原因及解決方法

網上查到的grant方式大多會報錯,主要原因是MySQL版本8.0後不能再使用原來的方式

查詢MySQL版本

SELECT version();

在8.0版本下

grant all privileges on test.* to test@'%' identified by '123456'; 

報錯

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'identified by '123456'' at line 1

正確的grant方式

create user test@'localhost' identified by '123456';
grant all privileges on test.* to test@'localhost';
flush privileges;

MySQL8.0密碼登錄不上

alter user test@'localhost' identified with mysql_native_password by '123456';

補充:MySQL ERROR 1064 (42000)——不管怎樣grant總是報錯,怎麼回事?

用過MySQL的朋友都知道,經常會有一些grant(授權)操作,不知道你有沒有遇到過這樣的問題。

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘identified by ‘123456’’ at line 1

MySQL grant的SQL

粘貼到終端執行,報錯!
每個字母敲後執行,又報錯!
反復確認很多遍執行,又又報錯!

都要瘋瞭,怎麼辦。別急,接著看文章。

版本的不同導致

首先,你先檢查一下你的MySQL版本, 大多數執行報錯的MySQL版本是8.0的,通過記憶甚至盲打命令都不層報錯的,估計通常都是用的最多的5.7瞭。信不信呢?

用真實數據測試

1.先用MySQL 8.0試一下

mysql> grant all privileges on test.* to test@'%' identified by '123456';  
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'identified by '123456'' at line 1

報錯瞭

2.再用MySQL 5.7試一下

mysql> grant all privileges on test.* to test@'%' identified by '123456';    
Query OK, 0 rows affected, 1 warning (0.08 sec)
mysql> flush privileges;

成功。

細心的朋友有沒有註意到返回結果裡有一個信息:1 warning,是什麼內容呢?

mysql> show warnings;
+---------+------+------------------------------------------------------------------------------------------------------------------------------------+
| Level   | Code | Message                                                                                                                            |
+---------+------+------------------------------------------------------------------------------------------------------------------------------------+
| Warning | 1287 | Using GRANT for creating new user is deprecated and will be removed in future release. Create new user with CREATE USER statement. |
+---------+------+------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

原來在MySQL5.7的時候,官方就提示瞭,這個語法SQL將要被棄用瞭。

正確的執行賦權

那麼在MySQL8.0版本及以後,我們如何正確執行grant呢?

先創建用戶,再賦予授權。

mysql> create user test@'localhost' identified by '123456';
Query OK, 0 rows affected (0.10 sec)

mysql> grant all privileges on test.* to test@'localhost';
Query OK, 0 rows affected (0.17 sec)

mysql> flush privileges;
Query OK, 0 rows affected (0.18 sec)

這個方法也適用MySQL5.7版本,所以建議大傢以後使用這種方式賦權,一鍵建用戶加賦權官方已經棄用瞭。

到此這篇關於MySQL在grant時報錯ERROR 1064 (42000)的文章就介紹到這瞭,更多相關mysql  grant報錯內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: