MySQL连接时提示ERROR 2002 (HY000)解决方案

问题现象:

用mysql -u root -p连接MySQL时,提示如下错误:

bash 复制代码
root@IBelieveICanFly:~# mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

系统环境如下:

bash 复制代码
# MySQL版本
root@host1:~# mysql --version
mysql  Ver 14.14 Distrib 5.7.42, for Linux (x86_64) using  EditLine wrapper

# 系统版本
root@host1:~# cat /etc/os-release 
NAME="Ubuntu"
VERSION="18.04.6 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.6 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

一、临时解决方案:

改为以下命令连接

bash 复制代码
root@host1:~# mysql -h 127.0.0.1 -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 90527026
Server version: 5.5.5-10.4.22-MariaDB Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

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> 

二、永久解决方案

修改mysql配置文件,可以是/etc/mysql/my.cnf或者/etc/mysql/conf.d/mysql.cnf,以下以/etc/mysql/conf.d/mysql.cnf为例。在[mysql]节中添加protocol=tcp。

bash 复制代码
[mysql]
protocol=tcp

保存即可。

bash 复制代码
root@host1:~# mysql -u root -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 90538418
Server version: 5.5.5-10.4.22-MariaDB Source distribution

Copyright (c) 2000, 2023, Oracle and/or its affiliates.

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> 
相关推荐
fenglllle4 分钟前
MySQL explain format的差异
数据库·mysql
哈哈不让取名字42 分钟前
用Pygame开发你的第一个小游戏
jvm·数据库·python
程序员敲代码吗43 分钟前
Python异步编程入门:Asyncio库的使用
jvm·数据库·python
liux35281 小时前
MySQL主从复制技术全面解析:从基础原理到高级架构实践(八)
mysql
a程序小傲1 小时前
听说前端又死了?
开发语言·前端·mysql·算法·postgresql·深度优先
志凌海纳SmartX1 小时前
榫卯企业云平台:让企业自建云更简单
数据库
老邓计算机毕设1 小时前
SSM学生信息管理系统ow05a(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面
数据库·学生信息管理系统·ssm 框架·高校教育管理
小Mie不吃饭1 小时前
MySQL慢查询日志全解析:从配置到优化实践
mysql
Access开发易登软件2 小时前
数据处理中的两大基石:何时选择Excel,何时考虑Access
数据库·信息可视化·excel·vba·access