go runtime_error ai_generated true

sql: transaction has already been committed or rolled back

ID: go/database-sql-tx-committed

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-07-12First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.21 active

Root Cause

Attempting to execute a query on a transaction that has already been committed or rolled back.

generic

中文

在已提交或回滚的事务上执行查询。

Workarounds

  1. 90% success
    tx, err := db.BeginTx(ctx, nil)
    if err != nil {
        // handle
    }
    // defer tx.Rollback() to ensure cleanup
    if err := tx.Commit(); err != nil {
        // handle
    }
  2. 70% success
    Check the transaction state before executing queries.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Once a transaction is done, it cannot be reused.

  2. 80% fail

    Commit() can only be called once.