go runtime_error ai_generated true

sql: database is closed

ID: go/database-sql-max-open-connections

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-01-25First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.15 active
1.19 active

Root Cause

Attempting to use a database handle after calling db.Close(), resulting in an error.

generic

中文

在调用 db.Close() 后尝试使用数据库句柄,导致错误。

Workarounds

  1. 90% success
    Use a sync.Once to close the database only once: var closeOnce sync.Once; closeOnce.Do(func() { db.Close() })
  2. 70% success
    Check if db is nil before using: if db == nil { return errors.New("db is closed") }

Dead Ends

Common approaches that don't work:

  1. 50% fail

    May be impossible if the database is down or configuration changed.

  2. 90% fail

    All subsequent queries will fail, causing application malfunction.