Mysql: possible to get last inserted id?

Created on 11 Jun 2013  ·  6Comments  ·  Source: go-sql-driver/mysql

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

question

Most helpful comment

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

All 6 comments

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

thanks sir!

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

Ops typo. I fixed the code above. Thanks!

How to convert int instead of int64?

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

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

Was this page helpful?
0 / 5 - 0 ratings