MySQL 连接时尽量使用 127.0.0.1 而不是 localhost

楼主
是不是看到我的头像就像摁空格键
原因

Whenever you specify "localhost" or "localhost:port" as server, the MySQL client library will override this and try to connect to a local socket (named pipe on Windows). If you want to use TCP/IP, use "127.0.0.1" instead of "localhost". If the MySQL client library tries to connect to the wrong local socket, you should set the correct path as in your PHP configuration and leave the server field blank.

localhost 使用的 Linux socket,127.0.0.1 使用的是 tcp/ip

Q:为什么我使用 localhost 一直没出问题

因为你的本机中只有一个 mysql 进程, 如果你有一个 node1 运行在 3306, 有一个 node2 运行在 3307

mysql -u root -h localhost -P 3306
mysql -u root -h localhost -P 3307


都会连接到同一个 mysql 进程, 因为 localhost 使用 Linux socket, 所以 -P 字段直接被忽略了, 等价于

mysql -u root -h localhost
mysql -u root -h localhost


而 -h 默认是 localhost, 又等价于

mysql -u root
mysql -u root


为了避免这种情况(比如你在本地开发只有一个 mysql 进程,线上或者 qa 环境有多个 mysql 进程)最好的方式就是使用 IP

mysql -u root -h 127.0.0.1 -P 3307


编辑于 2019-11-28 16:14  
编辑于 2019-11-28 16:14  
编辑于 2019-11-28 16:15  
分享扩散:

沙发
发表于 2019-11-28 16:26:08
社区这个排版有点摸不透
板凳
发表于 2019-11-29 14:00:30
v2上的lihongjie0209么?https://www.v2ex.com/t/623596
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

4回帖数 1关注人数 6213浏览人数
最后回复于:2019-12-9 17:07

返回顶部 返回列表