无法连接 mysql 服务器

报错代码:
➜  ~ mysql -uroot -p
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
报错原因:
① mysql服务器没有开启

② mysql服务器开启了,但不能找到 socket 文件
概述 mysql 的连接方式:
mysql的登陆方式有两种,分别是socket和tcp/ip方式登陆

### socket(套接字)连接方式:

只能在mysql客户端和数据库实例在同一台服务器上的情况下使用(本地连接);

通常连接localhost是通过一个Unix域套接字文件进行,一般是/tmp/mysql.sock;

若套接字文件被删除了,本地客户就不能再连接了

### 登录实例后查询
mysql> show variables like 'socket';
+---------------+-----------------+
| Variable_name | Value           |
+---------------+-----------------+
| socket        | /tmp/mysql.sock |
+---------------+-----------------+
1 row in set (0.04 sec)

### 当然我们也可以通过socket文件登录数据库
➜  ~ mysql -uroot -proot -S /tmp/mysql.sock -- 用户名 + 密码 + Socket文件路径地址(可不带默认)
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
............. 省略部分
#### 注意事项:
mysql.sock必须是mysql中配置的文件且必须在/tmp下存在;若不存在则启动不了mysql

### TCP/IP连接方式:
➜  ~ mysql -uroot -proot -h 127.0.0.1 -- 用户名 + 密码 + ip:port
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
............. 省略部分

#### 说明概述
若通过tcp/ip地址连接mysql;它将先检查权限视图表,检测请求方的ip是否允许被连接
mysql> use mysql;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> select host, user from user;
+-----------+------------------+
| host      | user             |
+-----------+------------------+
| localhost | mysql.infoschema |
| localhost | mysql.session    |
| localhost | mysql.sys        |
| localhost | root             |
+-----------+------------------+
4 rows in set (0.00 sec)
    ① host 表示该用户只能通过localhost的ip访问此数据库
    ② host:% 表示任何ip都可以连接mysql实例
问题解决方案:
① 修改配置文件增加socket路径
       ➜  ~ vim /usr/local/etc/my.cnf
       [mysqld]
       socket=/tmp/mysql.sock
② 使用软连接将已经存在的mysql.sock软链到/tmp/mysql.sock
       ln -s /usr/local/xxx/mysql.sock  /tmp/mysql.sock

③ 最最最暴力解决方案;卸载mysql,mysql相关的全部删除;为了实践演示我本机mac删除卸载重装  
       ➜  ~ brew remove mysql
       ➜  ~ brew cleanup
       ➜  ~ launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
       ➜  ~ rm ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
       ➜  ~ sudo rm -rf /usr/local/var/mysql
       ➜  ~ brew install mysql
       ➜  ~ launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist --设置开机启动
        /Users//Library/LaunchAgents/homebrew.mxcl.mysql.plist: service already loaded
posted @ 2025-08-13 12:30  寻码疹  阅读(17)  评论(0)    收藏  举报