go
runtime_error
ai_generated
true
sql: 事务已提交或回滚
sql: transaction has already been committed or rolled back
ID: go/database-sql-tx-commit-rollback
80%修复率
86%置信度
0证据数
2024-03-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 1.14 | active | — | — | — |
| 1.18 | active | — | — | — |
根因分析
对已最终确定的事务调用 Commit() 或 Rollback(),导致错误。
English
Calling Commit() or Rollback() on a transaction that has already been finalized, leading to an error.
解决方案
-
90% 成功率
Use defer with a check: defer func() { if err := tx.Rollback(); err != sql.ErrTxDone { log.Fatal(err) } }() -
85% 成功率
Track transaction state with a boolean: committed := false; if err := tx.Commit(); err == nil { committed = true }
无效尝试
常见但无效的做法:
-
70% 失败
Transaction state is already final; continuing may lead to data inconsistency.
-
90% 失败
Rollback will also fail because the transaction is already done.