背景
在远程连接mysql的时候应该都碰到过,root用户无法远程连接mysql,只可以本地连,对外拒绝连接。
通常需要建立一个允许远程登录的数据库帐户,这样才可以进行在远程操作数据库。
正文
方法如下:
默认情况下MYSQL数据库的系统数据库mysql系统表user内用户权限只提供localhost本机登陆;
需要更改权限才能实现远程连接MYSQL数据库。
可以通过以下方式来确认:
1、现在远程服务器上以本地方式登录mysql服务器。
root#mysql -h localhost -uroot -p
Enter password: **********
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.12-log MySQL Community Server (GPL)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
2、切换当前数据库为mysql(此DB存放MySQL的各种配置信息)
mysql> use mysql;
Database changed
3、检索user表中的用户的权限情况。
mysql> select host,user from user;
+-----------+------------+
| host | user |
+-----------+------------+
| localhost | mysql.sys |
| localhost | root |
+-----------+------------+
2 rows in set (0.00 sec)
由此可以看出,root只能以localhost的主机方式访问。
4、给root用户授权,允许其远程连接服务器
mysql> grant all privileges on *.* to 'root'@'%' identified by '123456' with grant option;
Query OK, 0 rows affected, 1 warning (0.01 sec)
%表示是所有的外部机器,如果指定某一台机,就将%改为相应的机器名;‘root’则是指要使用的用户名。
5、使授权生效
mysql> flush privileges;
Query OK, 0 rows affected (0.03 sec)
运行此句才生效,或者重启MySQL。
6、再次查看用户权限
mysql> select host,user from user;
+-----------+------------+
| host | user |
+-----------+------------+
| % | root |
| localhost | mysql.sys |
| localhost | root |
+-----------+------------+
3 rows in set (0.00 sec)
可以看出已经添加了一个新的用户
退出,试试效果…现在可以成功远程登录了…