sql.ErrConnDone
GoERRORNotableDatabase

sql: connection is already closed

Quick Answer

Do not hold a *sql.Conn across goroutines or after calling Close; obtain a new connection for each request.

What this means

Returned when a database operation is attempted on a connection that has been returned to the pool or explicitly closed. Indicates incorrect connection lifecycle management.

Why it happens
  1. 1*sql.Conn.Close called and then the connection used again
  2. 2Connection returned to the pool and then an operation attempted on it

Fix

Use db.QueryContext instead

Use db.QueryContext instead
// Prefer db methods over raw *sql.Conn
row := db.QueryRowContext(ctx, query, args...)

Why this works

Using db.QueryRowContext lets the pool manage connection lifecycle automatically.

Code examples
Detectgo
err := conn.QueryRowContext(ctx, q).Scan(&v)
if errors.Is(err, sql.ErrConnDone) {
    fmt.Println("connection closed")
}
Acquire per requestgo
conn, err := db.Conn(ctx)
defer conn.Close()
conn.QueryRowContext(ctx, q)
Use db directlygo
// pool manages connections automatically
db.QueryRowContext(ctx, q, id).Scan(&v)
Same error in other languages
Sources
Official documentation ↗

Go standard library

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Go errors