# sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) 在无效事务回滚之前无法重新连接

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

## 根因

之前的数据库操作失败，导致事务处于无效状态。在事务显式回滚之前，后续查询会失败。

## 版本兼容性

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

## 解决方案

1. **** (98% 成功率)
   ```
   try:
    session.execute(...)
except Exception:
    session.rollback()
    raise
   ```
2. **** (95% 成功率)
   ```
   @pytest.fixture
def db_session():
    session = Session()
    yield session
    session.rollback()
    session.close()
   ```
3. **** (90% 成功率)
   ```
   with session.begin():
    session.execute(...)
# automatically rolls back on exception
   ```

## 无效尝试

- **** — This is disruptive and does not address the application-level transaction handling issue. (90% 失败率)
- **** — The issue is not about pool size but about transaction state. (85% 失败率)
- **** — Retrying without rollback will keep failing. (95% 失败率)
