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> 
相关推荐
技术长镜头9 小时前
别再只说“走 B+Tree”:一条 SQL 在 InnoDB 中的完整寻址过程
后端·mysql
倒流时光三十年9 小时前
第六阶段 57 · ES|QL 与 SQL API(用 SQL 查 ES)
数据库·sql·elasticsearch
努力进修10 小时前
“数据心脏” 驱动能源自主:国产数据库支撑 Cemsol 实现固井全流程数字化闭环
数据库·人工智能·能源
vHelios10 小时前
SQL不会写?不会找关联表?复杂SQL语句编写逻辑实现思路请查收✉
数据库·sql
DB哥讲数据库11 小时前
【ClickHouse安装教程】从零开始部署高性能列式数据库(附ClickHouse安装包)
数据库·clickhouse
TDengine (老段)11 小时前
TDengine 第三方工具 — Telegraf、Kafka Connect、Flink、Spark
大数据·数据库·物联网·flink·kafka·时序数据库·tdengine
小白勇闯网安圈20 小时前
Django 响应对象、文件上传与类视图
数据库·django·sqlite
努力的小雨21 小时前
同一份 SQL 跑多套环境:Ksql 变量怎么用才安全
数据库
科技绘图21 小时前
快鲸GEO vs 传统AI搜索优化:全链路自动化与高效内容生产在转化闭环上的对比
数据库·人工智能·自动化
ltl21 小时前
数据库作为 LLM 记忆体:语义缓存、RAG 与一致性
数据库