stmt, err := db.Prepare("INSERT INTO users(name,email) VALUES(?,?)") res, err := stmt.Exec("John", "[email protected]") lastId, err := res.LastInsertId() if err != nil { fmt.Println("Error getting last insert ID") } else { fmt.Println("Last insert ID: ", lastId) }
type User struct { Id int Name string Email string } func createUser(name string, email string, db *sql.DB) (int64, error) { stmt, err := db.Prepare("INSERT INTO users(name,email) VALUES(?,?)") if err != nil { return 0, err } res, err := stmt.Exec(name, email) if err != nil { return 0, err } lastId, err := res.LastInsertId() if err != nil { return 0, err } return lastId, nil } func main() { db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database") if err != nil { log.Fatal(err) } defer db.Close() lastId, err := createUser("Jane", "[email protected]", db) if err != nil { log.Fatal(err) } fmt.Println("Last insert ID: ", lastId) }In this example, the LastInsertId method is used to retrieve the id of the last inserted row after executing an SQL statement that inserts a new user with a name and email into the users table. The createUser function encapsulates the SQL statement and error handling logic. The package library used is the standard database/sql package.