Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QueryRow().Scan() returns error if row doesn't exist

Tags:

go

I want to fetch one row from an sql database. I use the following code:

var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil {
    // log the error
}

For example: if a user with id=2 doesn't exist, then the method Scan returns an error.

Question:

Is there a way to avoid this error when a row doesn't exist? Because it's absolutely normal and I don't want to log such errors.

The only way I found is to use Query instead of QueryRow, but it is not convenient because I have to add for rows.Next() { .. every time when I want to fetch single row.

like image 307
Alex Rešatniak Avatar asked Mar 29 '17 11:03

Alex Rešatniak


1 Answers

Simply check for the error you don't want to log before logging:

var name string
row := db.Con().QueryRow("SELECT name FROM users WHERE id = 2;")
err := row.Scan(&name)

if err != nil && err != sql.ErrNoRows {
    // log the error
}
like image 150
Alexander Kohler Avatar answered Oct 30 '22 18:10

Alexander Kohler