go data_error ai_generated true

error: sql: Rows are closed

ID: go/database-sql-rows-iteration-error-after-close

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Attempting to iterate over database/sql Rows after they have been closed, typically due to premature defer row.Close() or double iteration.

generic

中文

在结果集关闭后尝试迭代,通常由于过早调用 defer row.Close() 或重复迭代。

Workarounds

  1. 95% success Defer rows.Close() after checking error and before iteration, but ensure iteration completes before close
    rows, err := db.QueryContext(ctx, query)
    if err != nil { return err }
    defer rows.Close()
    for rows.Next() { /* process */ }
    if err = rows.Err(); err != nil { return err }

Dead Ends

Common approaches that don't work:

  1. Calling rows.Close() at beginning of function 90% fail

    Deferring Close before iteration closes rows prematurely, causing 'Rows are closed' error on Next().