[ PROMPT_NODE_24694 ]
database
[ SKILL_DOCUMENTATION ]
# 数据库错误模式
PostgreSQL, MySQL, MongoDB, Redis 和 SQLite 中的常见数据库错误。
## 连接错误
### 连接被拒绝 (Connection Refused)
Error: connect ECONNREFUSED 127.0.0.1:5432
FATAL: connection refused
**原因**:
1. 数据库服务器未运行
2. 主机名/端口错误
3. 防火墙拦截连接
4. 已达到最大连接数
**诊断**:
bash
# 检查数据库是否运行
# PostgreSQL
pg_isready -h localhost -p 5432
# MySQL
mysqladmin ping -h localhost
# 检查端口
lsof -i :5432
netstat -an | grep 5432
# 检查进程
ps aux | grep postgres
ps aux | grep mysql
**解决方案**:
bash
# 启动数据库
# PostgreSQL
brew services start postgresql # macOS
sudo systemctl start postgresql # Linux
# MySQL
brew services start mysql # macOS
sudo systemctl start mysql # Linux
# Docker
docker start postgres_container
---
### 身份验证失败 (Authentication Failed)
FATAL: password authentication failed for user "username"
Access denied for user 'root'@'localhost'
**原因**:
1. 密码错误
2. 用户不存在
3. 身份验证方法错误
4. 用户缺乏权限
**解决方案**:
bash
# PostgreSQL - 重置密码
sudo -u postgres psql
ALTER USER username PASSWORD 'newpassword';
# MySQL - 重置密码
mysql -u root
ALTER USER 'username'@'localhost' IDENTIFIED BY 'newpassword';
FLUSH PRIVILEGES;
# 检查 pg_hba.conf 中的身份验证方法 (PostgreSQL)
# 将 'peer' 修改为 'md5' 或 'scram-sha-256' 以使用密码验证
---
### 数据库不存在 (Database Does Not Exist)
FATAL: database "mydb" does not exist
Unknown database 'mydb'
**解决方案**:
bash
# PostgreSQL
createdb mydb
# 或者在 psql 中:
CREATE DATABASE mydb;
# MySQL
mysql -u root -p -e "CREATE DATABASE mydb;"
# 查看现有数据库
psql -l # PostgreSQL
mysql -e "SHOW DATABASES;" # MySQL
---
### 连接超时 (Connection Timeout)
Error: Connection timed out
FATAL: connection timeout expired
**原因**:
1. 网络延迟
2. 数据库负载过高
3. 防火墙问题
4. DNS 解析缓慢
**解决方案**:
javascript
// 增加连接超时时间
// Node.js pg
const pool = new Pool({
connectionTimeoutMillis: 10000, // 10 秒
})
// Prisma
datasource db {
url = "postgresql://...?connect_timeout=10"
}
---
### 连接数过多 (Too Many Connections)
FATAL: too many connections for role "postgres"
ERROR 1040 (HY000): Too many connections
**原因**:
1. 连接泄漏(未关闭连接)
2. 连接池过大
3. 最大连接数设置过低