Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

possible to get last inserted id? #97

Closed
Dieterbe opened this issue Jun 11, 2013 · 6 comments
Closed

possible to get last inserted id? #97

Dieterbe opened this issue Jun 11, 2013 · 6 comments
Assignees
Labels

Comments

@Dieterbe
Copy link

after executing an insert, can get the last inserted id? this is a pretty common feature with mysql

@ghost ghost assigned julienschmidt Jun 11, 2013
@julienschmidt
Copy link
Member

Just use db.Exec and get the last inserted id from the result.

In general db.Exec should be used for every CREATE / INSERT / UPDATE / DELETE.

package main

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "user:pass@/dbname")
    if err != nil {
        panic("Error opening DB:", err.Error())
    }
    defer db.Close()

    someParam := "value"

    if res, err := db.Exec(`INSERT INTO foo VALUES("bar", ?))`, someParam)
    if err != nil {
        println("Exec err:", err.Error())
    } else {
        id, err := res.LastInsertId()
        if err != nil {
            println("Error:", err.Error())
        } else {
            println("LastInsertId:", id)
        }
    }
} 

See also:
http://golang.org/pkg/database/sql/#DB.Exec
http://golang.org/pkg/database/sql/#Result

@Dieterbe
Copy link
Author

thanks sir!

@WuErPing
Copy link

WuErPing commented Jun 9, 2015

    if err == nil {
        println("LastInsertId:", id)
    } else {
        println("Error:", err.Error())
    }

@julienschmidt
Copy link
Member

Ops typo. I fixed the code above. Thanks!

@ORESoftware
Copy link

How to convert int instead of int64?

strconv.Itoa(id) => cannot use id (type int64) as type int in argument to strconv.Itoa

@methane
Copy link
Member

methane commented Oct 26, 2018

It's a general Go newbie question. Don't ask such question here.

@go-sql-driver go-sql-driver locked as resolved and limited conversation to collaborators Oct 26, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

5 participants