MySQL 远程连接

333 阅读2分钟

开放 Mysql 的远程连接

在服务器上登录 mysql,然后执行以下的命令。

登录 mysql:

mysql -u root -p

执行赋权的命令:

MySQL> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY '123456' WITH GRANT OPTION; MySQL> flush privileges;

也可以直接重启 mysql。

service mysql restart

远程连接 MySQL

在本地连接 mysql,我们可以使用 mysql workbench,这是一款英文的 mysql 的客户端。

连接的时候出现错误:Can't connect to MySQL server on Ip地址 (111 "Connection refused")

检查防火墙

先检查防火墙的 3306 端口是不是放开了。这台服务器使用的是 iptables,打开 iptables,配置 3306 端口。

vi /etc/sysconfig/iptables # Firewall configuration written by system-config-firewall# Manual customization of this file is not recommended.*filter:INPUT ACCEPT [0:0]:FORWARD ACCEPT [0:0]:OUTPUT ACCEPT [0:0]-A INPUT -p tcp -m tcp --dport 10100:10180 -j ACCEPT-A INPUT -p tcp -m tcp --dport 21 -j ACCEPT-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT-A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT-A INPUT -j REJECT –reject-with icmp-host-prohibited-A FORWARD -j REJECT –reject-with icmp-host-prohibitedCOMMIT

重启防火墙

/etc/init.d/iptables restart

检查my.cnf

在 my.cnf 的配置文件中,有参数控制它是否运行在网络上。例如查看这个my.cnf

vi my.cnf

如果是老的版本,使用#屏蔽skip-networking,如下。

#skip-networking

如果是新的版本,使用#屏蔽bind-address

#bind-address  = 127.0.0.1

或者指定允许访问的 ip

#bind-address = 192.168.1.2

然后重启 mysql。

service mysql restart

这里是用文件的方式来启动 mysql,你可以用服务的方式。

在屏蔽#skip-networking后,再远程连接 mysql 就 OK 了。

附录iptables防火墙的命令

#查询防火墙状态:[root@localhost ~]# service iptables status
#停止防火墙:[root@localhost ~]# service iptables stop
#启动防火墙:[root@localhost ~]# service iptables start
#重启防火墙:[root@localhost ~]# service iptables restart
#永久关闭防火墙:[root@localhost ~]# chkconfig iptables off
#永久关闭后启用:[root@localhost ~]# chkconfig iptables on
#编辑防火墙规则vi /etc/sysconfig/iptables
#重启防火墙的其他方式/etc/init.d/iptables restart