ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'

发布时间 2023-04-23 14:33:36作者: hkgan

  今天执行mysql操作的时候出现了错误:ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'问题

1:首先检查是否安装了mysql-server了 

sudo apt-get install mysql-server to install mysql on ubuntu

  sudo apt-get install mysql-server to install mysql on ubuntu, 如果mysql-server已经存在了,那么在去尝试一下是否成功,如果还是这个错误的话那么就是文件/var/run/mysqld/mysqld.sock 不存在。

2:如果/var/run/mysqld/mysqld.sock文件不存在应该怎么办?

  执行 vim   /etc/mysql/my.cnf
       将会看到内容如下:
#
# The MySQL database server configuration file.
#
# You can copy this to one of:
# - "/etc/mysql/my.cnf" to set global options,
# - "~/.my.cnf" to set user-specific options.
# 
# One can use all long options that the program supports.
# Run program with --help to get a list of available options and with
# --print-defaults to see which it would actually understand and use.
#
# For explanations see
# http://dev.mysql.com/doc/mysql/en/server-system-variables.html
 
#
# * IMPORTANT: Additional settings that can override those from this file!
#   The files must end with '.cnf', otherwise they'll be ignored.
#
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mysql.conf.d/

  你的mysql的配置在/etc/mysql/mysql.conf.d目录下的mysqld.cnf文件,打开如下:

  可以看到:bind-address = 127.0.0.1      socket = /var/run/mysqld/mysqld.sock  等信息

   我的虚拟机是/var/run下面没有mysqld目录,执行下面命令,然后目录和sock文件就都有了

sudo mkdir -p /var/run/mysqld
sudo chown mysql /var/run/mysqld/
sudo service mysql restart

  现在就都有了:

  然后执行:mysql -u root -p   然后提示你输入密码,即可, 如下图所示:

mysql -u root -p 你的mysql密码

就可以了 ......