Search code examples
mysqlgosqlx

How to check if row exists using sqlx?


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?


Solution

  • 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)
    }