在連接 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 |