1、错误信息

登录服务器,使用root用户连接mysql时出现错误提示:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

2、mysql.sock 文件有什么用

mysql 支持 socket 和 TCP/IP 连接。那么 mysql.sock 这个文件有什么用呢?连接localhost通常通过一个Unix域套接字文件进行,一般是/tmp/mysql.sock。如果套接字文件被删除了,本地客户就不能连接。/tmp 文件夹属于临时文件,随时可能被删除。

2.1 TCP 连接(如果报错 /tmp/mysql.sock,你可以尝试这种方式连接)

mysql -uroot -h 127.0.0.1 -p

2.2 socket 连接(如果一定要用这种方式连接,你可以以下解决方式)

mysql -uroot -p

3、解决方式

3.1 重启mysql,还是报同样的错

[root@centos7 mysql]# /etc/init.d/mysqld restart
Shutting down MySQL....................                    [  确定  ]
Starting MySQL.............................................[  确定  ]
[root@centos7 mysql]# mysql -uroot -p
Enter password:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

 

3.2 看一下myf

[root@centos7 mysql]# more myf |grep sock
socket=/var/lib/mysql/mysql.sock
socket=/var/lib/mysql/mysql.sock

可以看到我的mysql已经声明了mysql.sock的文件位置,而错误提示为/tmp/mysql.sock; 也就是说虽然我的mysql声明了sock文件的位置,但是客户端在连接的时候, linux系统总是去/tmp目录下去找,找到了原因,就可以对症下药了:

3.3 为mysql.sock创建链接文件

[root@centos7 mysql]# ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock

3.4 然后再次连接mysql,成功连接

[root@centos7 mysql]# ln -s /var/lib/mysql/mysql.sock /tmp/mysql.sock
[root@centos7 mysql]# mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.28 MySQL Community Server (GPL)

Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>

end,本文结束,希望对大家有所帮助!

更多推荐

【mysql报错】ERROR 2002 (HY000): Can‘t connect to local MySQL server through socket