Skip to content
\n
$ go run q1717.go\nlast insert id: 1\nlast insert id: 2\nid: 1, name: Bob\nid: 2, name: Alice\nid: 3, name: Mary\nid: 4, name: Jane\nid: 5, name: Lisa\n
\n
\n

However, when I run the queries using this driver and call result.LastInsertId(), the correct ID is returned even if I supplied it myself.

\n
\n

This driver doesn't query SELECT LAST_INSERT_ID(). This driver just returns what MySQL protocol returns.
\nSo you should read the mysql_insert_id, not LAST_INSERT_ID().

\n
\n

Another difference from mysql_insert_id() is that LAST_INSERT_ID() is not updated if you set an AUTO_INCREMENT column to a specific nonspecial value.
\nhttps://dev.mysql.com/doc/refman/8.4/en/information-functions.html#function_last-insert-id

\n
","upvoteCount":1,"url":"https://github.com/go-sql-driver/mysql/discussions/1717#discussioncomment-13176590"}}}
Discussion options

You must be logged in to vote

However, when I run the queries using this driver, the LastInsertId() returns THE LAST inserted row.

REALLY?

// https://github.com/go-sql-driver/mysql/discussions/1717

package main

import (
	"database/sql"
	"fmt"

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

// Use example in https://dev.mysql.com/doc/refman/8.0/en/information-functions.html#function_last-insert-id
func main() {
	db, err := sql.Open("mysql", "root:my-secret-pw@tcp(127.0.0.1:3306)/test")
	if err != nil {
		panic(err)
	}

	res, err := db.Exec("INSERT INTO t VALUES (NULL, 'Bob')")
	if err != nil {
		panic(err)
	}
	last, err := res.LastInsertId()
	fmt.Printf("last insert id: %d\n", last)

	res, err = db.Exec("INSERT INTO t VALU…

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@stephenafamo
Comment options

Answer selected by stephenafamo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants