Db Connection Not Closed (ARCH5084)
Key go.performance.db-connection-not-closed · Severity error · Category performance
If the *sql.Rows returned by a query is never closed, the underlying connection is not returned to the pool and the pool drains. Close it with defer rows.Close().
Incorrect
Section titled “Incorrect”func ids(db *sql.DB) ([]int, error) { rows, err := db.Query("SELECT id FROM users") if err != nil { return nil, err } var out []int for rows.Next() { var id int rows.Scan(&id) out = append(out, id) } return out, nil}Correct
Section titled “Correct”func ids(db *sql.DB) ([]int, error) { rows, err := db.Query("SELECT id FROM users") if err != nil { return nil, err } defer rows.Close() var out []int for rows.Next() { var id int rows.Scan(&id) out = append(out, id) } return out, nil}Add defer rows.Close() after opening the *sql.Rows or connection.