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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With