go runtime_error ai_generated true

sql: 事务已提交或回滚

sql: transaction has already been committed or rolled back

ID: go/database-sql-tx-commit-rollback

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 90% 成功率
    Use defer with a check: defer func() { if err := tx.Rollback(); err != sql.ErrTxDone { log.Fatal(err) } }()
  2. 85% 成功率
    Track transaction state with a boolean: committed := false; if err := tx.Commit(); err == nil { committed = true }

无效尝试

常见但无效的做法:

  1. 70% 失败

    Transaction state is already final; continuing may lead to data inconsistency.

  2. 90% 失败

    Rollback will also fail because the transaction is already done.