How to retrieve the last inserted ID (auto-increment) after an INSERT operation in Go?

In Go, you can retrieve the last inserted ID (auto-increment) after an INSERT operation using the LastInsertId method provided by the sql.Result object.

Here's an example of how you can retrieve the last inserted ID in Go:

package main import ( "database/sql" "fmt" "log" _ "github.com/go-sql-driver/mysql" ) func main() { // Open a connection to the database db, err := sql.Open("mysql", "username:password@tcp(localhost:3306)/database") if err != nil { log.Fatal(err) } defer db.Close() // Perform an INSERT operation result, err := db.Exec("INSERT INTO users (name, email) VALUES (?, ?)", "John Doe", "[email protected]") if err != nil { log.Fatal(err) } // Retrieve the last inserted ID lastInsertedID, err := result.LastInsertId() if err != nil { log.Fatal(err) } fmt.Printf("Last inserted ID: %d\n", lastInsertedID) }

In this example, we first open a connection to the MySQL database using the sql.Open function. Then, we perform an INSERT operation using the db.Exec method, which returns a sql.Result object. We can then call the LastInsertId method on the sql.Result object to retrieve the last inserted ID.

Note: Make sure to replace the database connection string (username:password@tcp(localhost:3306)/database) with your actual database credentials and connection details.