Karlom
Karlom

Reputation: 14834

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?

Upvotes: 3

Views: 6601

Answers (2)

Jonathan Hall
Jonathan Hall

Reputation: 79594

The return value from Exec, Result is not meant to be accessed directly--it's an object with two methods to call, one of which is LastInsertId().

lastId, err := resultPost.LastInsertId()
if err != nil {
    panic(err)
}
fmt.Println("LastInsertId: ", lastId)

Upvotes: 5

GMB
GMB

Reputation: 222462

Looks like you just need :

resultPost.LastInsertId()

For more information, search for LastInsertId in this documentation

Upvotes: 4

Related Questions