mysqlsqlgosql-insertsqlx

How to get id of last inserted row from sqlx?


I'd like to get back the id of the last post inserted into MySql database using sqlx:

resultPost, err := shared.Dbmap.Exec("INSERT INTO post (user_id, description, link) VALUES (?, ?, ?)", userID, title, destPath)
if err != nil {
    log.Println(err)
    c.JSON(
        http.StatusInternalServerError,
        gin.H{"error": "internal server error"})
}

fmt.Println("resultPost is:", resultPost)

The problem is that the resultPost is printed as an object:

resultPost is: {0xc420242000 0xc4202403a0}

So I'm wondering what is the correct way to extract the id of the row just inserted?


Solution

  • Looks like you just need :

    resultPost.LastInsertId()
    

    For more information, search for LastInsertId in this documentation