python
data_error
ai_generated
true
sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) 在无效事务回滚之前无法重新连接
sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) Can't reconnect until invalid transaction is rolled back
ID: python/pytest-sqlalchemy-connection-closed
80%修复率
88%置信度
0证据数
2025-09-01首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
之前的数据库操作失败,导致事务处于无效状态。在事务显式回滚之前,后续查询会失败。
English
A previous database operation failed, leaving the transaction in an invalid state. Subsequent queries fail until the transaction is explicitly rolled back.
解决方案
-
98% 成功率
try: session.execute(...) except Exception: session.rollback() raise -
95% 成功率
@pytest.fixture def db_session(): session = Session() yield session session.rollback() session.close() -
90% 成功率
with session.begin(): session.execute(...) # automatically rolls back on exception
无效尝试
常见但无效的做法:
-
90% 失败
This is disruptive and does not address the application-level transaction handling issue.
-
85% 失败
The issue is not about pool size but about transaction state.
-
95% 失败
Retrying without rollback will keep failing.