更新时间:2022-12-02 14:50:47
当您只使用localhost"时,MySQL 客户端库会尝试使用 Unix 域套接字而不是 TCP/IP 连接进行连接.错误告诉您,名为 MySQL
的套接字不能用于建立连接,可能是因为它不存在(错误号 2).
When you use just "localhost" the MySQL client library tries to use a Unix domain socket for the connection instead of a TCP/IP connection. The error is telling you that the socket, called MySQL
, cannot be used to make the connection, probably because it does not exist (error number 2).
来自 MySQL 文档:
在 Unix 上,MySQL 程序特别对待主机名 localhost,在与其他方式相比,这可能与您期望的方式不同基于网络的程序.对于到 localhost、MySQL 程序的连接尝试使用 Unix 套接字文件连接到本地服务器.即使给出 --port 或 -P 选项来指定端口,也会发生这种情况数字.确保客户端与客户端建立 TCP/IP 连接本地服务器,使用 --host 或 -h 指定主机名值127.0.0.1,或本地服务器的 IP 地址或名称.您还可以通过以下方式显式指定连接协议,即使对于 localhost 也是如此使用 --protocol=TCP 选项.
On Unix, MySQL programs treat the host name localhost specially, in a way that is likely different from what you expect compared to other network-based programs. For connections to localhost, MySQL programs attempt to connect to the local server by using a Unix socket file. This occurs even if a --port or -P option is given to specify a port number. To ensure that the client makes a TCP/IP connection to the local server, use --host or -h to specify a host name value of 127.0.0.1, or the IP address or name of the local server. You can also specify the connection protocol explicitly, even for localhost, by using the --protocol=TCP option.
有几种方法可以解决这个问题.
There are a few ways to solve this problem.
127.0.0.1
而不是 localhost
来做到这一点.不过,Unix 套接字使用起来可能更快、更安全.php.ini
:打开 MySQL 配置文件 my.cnf
以查找 MySQL 创建套接字的位置,并将 PHP 的 mysqli.default_socket
设置为该路径.在我的系统上是 /var/run/mysqld/mysqld.sock
.打开连接时直接在PHP脚本中配置socket.例如:
127.0.0.1
instead of localhost
when you connect. The Unix socket might by faster and safer to use, though.php.ini
: open the MySQL configuration file my.cnf
to find where MySQL creates the socket, and set PHP's mysqli.default_socket
to that path. On my system it's /var/run/mysqld/mysqld.sock
.Configure the socket directly in the PHP script when opening the connection. For example:
$db = new MySQLi('localhost', 'kamil', '***', '', 0,
'/var/run/mysqld/mysqld.sock')
mysqli :: mysqli():(HY000/2002):无法通过套接字'MySQL'连接到本地MySQL服务器(2)
错误2002(HY000):无法通过套接字'/var/lib/mysql/mysql.sock'连接到本地MySQL服务器
mysqli::mysqli(): (HY000/2002): 无法通过 socket 'MySQL' 连接到本地 MySQL 服务器 (2)
mysqli::mysqli(): (HY000/2002): 无法通过套接字 'MySQL' 连接到本地 MySQL 服务器 (2)
MAMP-phpMyAdmin#2002-无法通过套接字'/Applications/MAMP/tmp/mysql/mysql.sock'连接到本地MySQL服务器