错误信息:
ERROR 1045 (28000): Access denied for user 'username'@'localhost' (using password: YES)
解决方案: - 检查用户名和密码是否正确 - 确保用户有远程连接权限(如果从远程连接)
GRANT ALL PRIVILEGES ON *.* TO 'username'@'%' IDENTIFIED BY 'password';
FLUSH PRIVILEGES;
0.0.0.0
(允许所有IP)或特定IP# /etc/mysql/my.cnf
[mysqld]
bind-address = 0.0.0.0
错误信息:
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
解决方案: - 检查MySQL服务是否运行
sudo systemctl status mysql
sudo systemctl start mysql
sudo ufw allow mysql
错误信息:
psql: FATAL: password authentication failed for user "username"
解决方案:
- 检查pg_hba.conf
文件配置
# /etc/postgresql/version/main/pg_hba.conf
# 添加或修改以下行
host all all 0.0.0.0/0 md5
sudo systemctl reload postgresql
错误信息:
psql: could not connect to server: Connection timed out
解决方案: - 检查PostgreSQL是否监听正确端口(默认5432)
sudo netstat -tulnp | grep postgres
postgresql.conf
中的监听设置# /etc/postgresql/version/main/postgresql.conf
listen_addresses = '*'
port = 5432
解决方案: - 开放数据库端口
# MySQL
sudo ufw allow 3306
# PostgreSQL
sudo ufw allow 5432
# MongoDB
sudo ufw allow 27017
错误信息:
ERROR 1040 (HY000): Too many connections
解决方案: - 增加最大连接数(MySQL示例)
SET GLOBAL max_connections = 200;
# /etc/mysql/my.cnf
[mysqld]
max_connections = 200
解决方案: - 检查系统内存使用情况
free -h
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
telnet db_host 3306
nc -zv db_host 5432
# MySQL
sudo tail -f /var/log/mysql/error.log
# PostgreSQL
sudo tail -f /var/log/postgresql/postgresql-version-main.log
ps aux | grep mysql
ps aux | grep postgres
df -h
通过以上方法,可以解决Linux系统中大多数常见的数据库连接问题。如果问题仍然存在,建议查阅特定数据库的官方文档或社区支持。