3

Using sqlx, I'd like to know query MySql database to know whether a query on MySql returns empty rows:

So following this, I came up with

var result model.Post
err := database.SQL.Get(&result, "SELECT * FROM post WHERE post_id=? AND user_id=? LIMIT 1", postID, userID)
if err == sql.ErrNoRows { 
    log.Println(err)
    log.Println("post not found")
} else { 
    log.Println("post found")
}

But I always get post found, despite the fact that there is no row.

What could be wrong here and how can I fix it?

Karlom
  • 8,901
  • 19
  • 57
  • 100
  • Possible duplicate of [I want to check if record exist and if not exist then i want to insert that record to database using golang](https://stackoverflow.com/questions/49449087/i-want-to-check-if-record-exist-and-if-not-exist-then-i-want-to-insert-that-reco) – Flimzy Feb 09 '19 at 09:27

1 Answers1

6

If row found err will be nil

Here is working example:

var result model.Post
err := database.SQL.Get(&result, "SELECT * FROM post WHERE post_id=? AND user_id=? LIMIT 1", postID, userID)

switch err {
case nil:
    log.Printf("user found: %+v\n", user)
case sql.ErrNoRows:
    log.Println("user NOT found, no error")
default:
    log.Printf("error: %s\n", err)
}