# Go: sql: database is closed

**Code:** `sql: database is closed / driver: bad connection` · **Category:** Go · **Seen on:** Go

The `*sql.DB` handle was closed (or the connection died) before the query ran.

## 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

1. Open one `*sql.DB` at startup and close at shutdown
2. `db.SetConnMaxLifetime(3*time.Minute)` and `SetMaxIdleConns`
3. Retry on `driver.ErrBadConn`

## Detailed fix by platform

### Go

1. `db.SetConnMaxLifetime(3 * time.Minute); db.SetMaxOpenConns(20); db.SetMaxIdleConns(10)`

## How to diagnose

1. **Close** — Called when?
2. **Lifetime** — Shorter than server timeout?
3. **Pool** — Single shared?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/go/sql-database-is-closed)
