Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 798
Karlom Avatar asked Oct 15 '25 15:10

Karlom


1 Answers

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)
like image 117
Flimzy Avatar answered Oct 18 '25 05:10

Flimzy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!