MySQL远程访问授权作为一个基础常规的操作,我本来是不打算写的,但是网上的文章确实太坑,MySQL已步入了8的时代很久了,网上依旧是老的文章不断的炒冷饭,相关命令错误百出,标题和内容完全不符。
本文主要讲解,在MySQL8中如何正确的配置远程访问用户,与MySQL5.7不同之处!
如果你只是想要把root用户允许远程访问,登录mysql后,你可以直接执行以下命令,以下远程授权适用于MySQL8也适用于MySQL5.7。
mysql -uroot -p
|---|-----------------| | 1 | mysql -uroot -p |
mysql> use mysql; mysql> update user set host = '%' where user ='root'; mysql> flush privileges; mysql> exit
|---------|------------------------------------------------------------------------------------------------------------------| | 1 2 3 4 | mysql> use mysql; mysql> update user set host = '%' where user ='root'; mysql> flush privileges; mysql> exit |
在MySQL5.7版本使用grant来进行用户授权
例:创建一个whsir用户,允许所有IP访问,密码是password
mysql> GRANT ALL PRIVILEGES ON *.* TO 'whsir'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION;
|---|--------------------------------------------------------------------------------------------------| | 1 | mysql> GRANT ALL PRIVILEGES ON *.* TO 'whsir'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION; |
但是从MySQL8版本开始,不能再使用GRANT创建用户,而是要先CREATE USER,然后使用GRANT授权。
上面的例子在MySQL8中的写法:
mysql> CREATE USER 'whsir'@'%' IDENTIFIED BY 'password'; mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; mysql> FLUSH PRIVILEGES;
|-------|------------------------------------------------------------------------------------------------------------------------------------------------------------| | 1 2 3 | mysql> CREATE USER 'whsir'@'%' IDENTIFIED BY 'password'; mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; mysql> FLUSH PRIVILEGES; |
附:查看用户相关信息
mysql> use mysql; mysql> select host,user,plugin from user;
|-----|---------------------------------------------------------------| | 1 2 | mysql> use mysql; mysql> select host,user,plugin from user; |