user1406186
user1406186

Reputation: 1002

Does db.Query return ErrNoRows?

I can't seem to get ErrNoRows from my db.query when a sql query is expected to return no results.

results, err := database.Query("SELECT title FROM accountProject WHERE accountID=? AND MATCH(title) AGAINST(?)", accountID, query)
if err != nil {
    if err == sql.ErrNoRows {
        return errProjectDoesNotExist
    }
    return err
}

Upvotes: 5

Views: 7923

Answers (1)

Thundercat
Thundercat

Reputation: 120941

The value sql.ErrNoRows is not returned from DB.Query or DB.QueryContext. The first call to Rows.Next returns false when the result set has no rows.

The value sql.ErrNoRows is returned from a call to Row.Scan on a placeholder row returned from DB.QueryRow or DB.QueryRowContext. The DB.QueryRow* methods return a placeholder row on error instead of returning an error directly.

If the application is looking for zero or one rows, use QueryRow instead of Query.

row := database.QueryRow("SELECT title FROM accountProject WHERE accountID=? AND MATCH(title) AGAINST(?)", accountID, query)
err := row.Scan( .... address of variables here ... )
if err == sql.ErrNoRows {
    return errProjectDoesNotExist
} else if err != nil {
    return err
}

Upvotes: 16

Related Questions