go runtime_error ai_generated true

sql: connection is already in use

ID: go/database-sql-conn-already-in-use

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.16 active
1.19 active

Root Cause

A database connection was returned to the pool while still being used by another goroutine, causing a race condition.

generic

中文

数据库连接在仍被其他 goroutine 使用时被返回到池中,导致竞争条件。

Workarounds

  1. 90% success
    Ensure each query uses its own connection properly: use db.QueryContext with a context and avoid sharing rows between goroutines.
  2. 75% success
    Use a mutex to serialize access to rows: var mu sync.Mutex; mu.Lock(); defer mu.Unlock(); rows.Scan(...)

Dead Ends

Common approaches that don't work:

  1. 80% fail

    May cause data corruption or panics due to concurrent access.

  2. 50% fail

    Doesn't fix the root cause; may delay the issue but not prevent it.