Go: sql: database is closed
The *sql.DB handle was closed (or the connection died) before the query ran.
sql: database is closeddriver: bad connectionsql: connection is already closedinvalid connectionsql: transaction has already been committed or rolled back Meaning
db.Close() was called too early — often with defer db.Close() in a function that returns while goroutines still use the handle. sql.DB is a long-lived pool and should be closed once at shutdown. driver: bad connection usually means the server dropped an idle connection; set SetConnMaxLifetime.
Common causes
- db.Close() in a short-lived function
- Pool shared after close
- Server closed idle connections (timeouts, proxies)
- Connection reset by DB restart
- Max lifetime longer than server timeout
⚡ Quick fix
- Open one
*sql.DBat startup and close at shutdown db.SetConnMaxLifetime(3*time.Minute)andSetMaxIdleConns- Retry on
driver.ErrBadConn
Detailed fix by platform
Go
db.SetConnMaxLifetime(3 * time.Minute); db.SetMaxOpenConns(20); db.SetMaxIdleConns(10)
How to diagnose
- Close — Called when?
- Lifetime — Shorter than server timeout?
- Pool — Single shared?
🔧 Still not fixed?
Many errors look alike. If the steps above didn’t solve it, one of these is probably what you’re facing:
Similar errors
- assignment mismatch: 1 variable but f returns 2 values Go: assignment mismatch: 1 variable but os.Open returns 2 values
- cannot assign to struct field m[k].f in map Go: cannot assign to struct field users["bob"].Age in map
- context canceled Go: context canceled (rpc error: code = Canceled desc = context canceled)
Most viewed in Go
Other ways to find it
Where this error sits
Origin: Application & API. Errors that are often confused with or caused by this one (click to open):
🧠 Still stuck? Analyze your error
Paste the full message, response headers or stack trace — we'll detect the platform and point to the most likely cause.
💬 What worked for others
No tips yet — did something else fix this for you?
Share what worked for you
Tips are checked by an editor before they appear. Links are removed.
Report a correction or suggest an improvement
Last updated 4 Nov 2026