# sqlalchemy.exc.PendingRollbackError: 在无效事务回滚之前无法重新连接。请先完整执行 rollback() 后再继续。

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

## 根因

之前的 SQL 操作失败（如违反约束），但会话未回滚。后续在同一会话上的操作会触发此错误，因为事务仍处于失败状态。

## 版本兼容性

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

## 解决方案

1. **** (95% 成功率)
   ```
   Explicitly rollback the session after any exception: try: session.commit() except: session.rollback() raise
   ```
2. **** (90% 成功率)
   ```
   Use a context manager pattern: with session.begin(): # operations - automatically rolls back on exception
   ```

## 无效尝试

- **** — close() does not reset the transaction state; it only releases connections. The next session usage still carries the failed transaction. (90% 失败率)
- **** — The error is persistent until rollback is explicitly called; retrying the same failed operation doesn't clear the invalid transaction flag. (100% 失败率)
