go network_error ai_generated true

error: sql: database is closed

ID: go/database-sql-connection-bad-connection

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2026-06-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.20 active
1.21 active

Root Cause

Attempting to use a database connection after the database has been closed, typically due to calling db.Close() prematurely.

generic

中文

在数据库关闭后尝试使用数据库连接,通常由于过早调用db.Close()。

Workarounds

  1. 95% success Use a single db instance and close only when shutting down
    db, err := sql.Open("driver", dsn)
    if err != nil { log.Fatal(err) }
    defer db.Close()
    // use db for all queries

Dead Ends

Common approaches that don't work:

  1. Reopening database for each query 70% fail

    Inefficient; use connection pool and defer close at application shutdown.