sçuçu
sçuçu

Reputation: 3070

Go func (*DB) Query return when such a row does not exist

Signature is func (db *DB) Query(query string, args ...interface{}) (*Rows, error).

What does Go func (*DB) Query return if the query and call is:

rows, err := db.Query("SELECT username FROM userstable WHERE username=$1", registerInstance.Username)

when there is no such row in the table userstable.

Does it return a non-nil error or return empty string value as Result and non-nil error is returned only when an error occurs?

Upvotes: 0

Views: 4155

Answers (1)

dave
dave

Reputation: 64657

In this case, you'll definitely want to use QueryRow instead of Query (assuming you'd only ever get one user with the same username).

From http://go-database-sql.org/retrieving.html

Go defines a special error constant, called sql.ErrNoRows, which is returned from QueryRow() when the result is empty. This needs to be handled as a special case in most circumstances. An empty result is often not considered an error by application code, and if you don’t check whether an error is this special constant, you’ll cause application-code errors you didn’t expect.

When using Query, you'll be looping over the results with something like:

rows, err := db.Query("SELECT username FROM userstable WHERE username=$1", registerInstance.Username)
if err != nil {
    log.Fatal(err)
}
defer rows.Close()
var users []User
for rows.Next() {
    user = User{}
    err := rows.Scan(&user.Username)
    if err != nil {
        log.Fatal(err)
    }
    users = append(users, user)
}
rows.Close()
if (len(users) == 0) {
    //handle this case
}

Upvotes: 1

Related Questions