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

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

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

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服务是否已经启动

ps -ef | grep mysql

 如果发现没有mysql服务,那请先启动mysql

3.2 重启mysql

/etc/init.d/

 3.3 如果启动mysql之后还是报错,看一下my.cnf

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

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

3.4 为mysql.sock创建链接文件

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


3.5 然后再次连接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>


 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值