在连接 MySQL 时, 虽然使用 localhost 或 127.0.0.1 都是连接到本机, 但连接的方式本质上是不同的。
连接 MySQL 时如果不加上 -h 参数, 会使用默认的 localhost 连接 MySQL, 而透过 localhost 连接 MySQL 是使用 Unix Socket (/var/lib/mysql/mysql.sock), 没有使 TCP/IP, 所以没有经过网络卡, 不会受防火墙的限制。而如果透过 127.0.0.1 连接 MySQL, 即在指令模式输入 mysql -h 127.0.0.1 连接 MySQL, 这便会使用 TCP/IP (使用 port 3306) 及经过网络卡传送资料。
有时发现可以用 localhost 连接, 但输入正确使用者名称及密码就不能连接到 127.0.0.1, 可能是网络设定的问题。
要检视相关资料, 可以登入 MySQL 后, 输入 status 指令, 便可以看到连线类型, 例如
localhost:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
$ mysql -h localhost -u root -p Enter password: Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 169731 Server version: 5.5.56-MariaDB MariaDB Server Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> status -------------- mysql Ver 15.1 Distrib 5.5.56-MariaDB, for Linux (x86_64) using readline 5.1 Connection id: 169731 Current database: Current user: root@localhost SSL: Not in use Current pager: stdout Using outfile: '' Using delimiter: ; Server: MariaDB Server version: 5.5.56-MariaDB MariaDB Server Protocol version: 10 Connection: Localhost via UNIX socket ### 连接透过 UNIX socket Server characterset: latin1 Db characterset: latin1 Client characterset: latin1 Conn. characterset: latin1 UNIX socket: /var/lib/mysql/mysql.sock ### 透过 UNix socket Uptime: 3 days 11 hours 44 min 26 sec |
127.0.0.1:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
$ mysql -h 127.0.0.1 -u root -p Enter password: Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 169803 Server version: 5.5.56-MariaDB MariaDB Server Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> status -------------- mysql Ver 15.1 Distrib 5.5.56-MariaDB, for Linux (x86_64) using readline 5.1 Connection id: 169803 Current database: Current user: root@localhost SSL: Not in use Current pager: stdout Using outfile: '' Using delimiter: ; Server: MariaDB Server version: 5.5.56-MariaDB MariaDB Server Protocol version: 10 Connection: 127.0.0.1 via TCP/IP ### 连接透过 TCP/IP Server characterset: latin1 Db characterset: latin1 Client characterset: latin1 Conn. characterset: latin1 TCP port: 3306 ### 透过 port 3306 Uptime: 3 days 11 hours 46 min 29 sec |