go network_error ai_generated true

错误:sql:数据库已关闭

error: sql: database is closed

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

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2026-06-15首次发现

版本兼容性

版本状态引入弃用备注
1.20 active
1.21 active

根因分析

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

English

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

generic

解决方案

  1. 95% 成功率 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

无效尝试

常见但无效的做法:

  1. Reopening database for each query 70% 失败

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