# sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) 服务器意外关闭了连接

- **ID:** `python/sqlalchemy-session-closed-connection`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

数据库连接被服务器关闭，通常是由于超时或网络问题，而会话仍在使用的连接已失效。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **Recreate the session using a fresh engine connection** (95% 成功率)
   ```
   from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://user:pass@localhost/db', pool_pre_ping=True)
Session = sessionmaker(bind=engine)
session = Session()
# Use session for queries
   ```
2. **Enable pool_pre_ping to check connection health** (90% 成功率)
   ```
   engine = create_engine('postgresql://user:pass@localhost/db', pool_pre_ping=True)
   ```

## 无效尝试

- **Restarting the database server** — Restarting the server does not fix the underlying issue of connection pooling or timeout settings. (75% 失败率)
- **Using session.commit() to retry** — Commit does not reset the connection; it only flushes pending changes. (85% 失败率)
