python runtime_error ai_generated true

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

sqlalchemy.exc.PendingRollbackError: Can't reconnect until invalid transaction is rolled back. Please rollback() fully before proceeding

ID: python/sqlalchemy-missing-session-commit

其他格式: JSON · Markdown 中文 · English
80%修复率
85%置信度
0证据数
2024-03-15首次发现

版本兼容性

版本状态引入弃用备注
1.4.x active
2.0.x active

根因分析

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

English

A previous SQL operation failed (e.g., constraint violation) but the session was not rolled back. Subsequent operations on the same session trigger this error because the transaction remains in a failed state.

generic

解决方案

  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

无效尝试

常见但无效的做法:

  1. 90% 失败

    close() does not reset the transaction state; it only releases connections. The next session usage still carries the failed transaction.

  2. 100% 失败

    The error is persistent until rollback is explicitly called; retrying the same failed operation doesn't clear the invalid transaction flag.