// Start a transaction tx, err := db.Begin() if err != nil { // handle error } // Perform some SQL statements _, err = tx.Exec("UPDATE users SET name='Alice' WHERE id=1") if err != nil { // handle error } _, err = tx.Exec("UPDATE users SET name='Bob' WHERE id=2") if err != nil { // handle error } // Commit transaction err = tx.Commit() if err != nil { // handle error }
tx, err := db.Begin() if err != nil { // handle error } defer func() { // Rollback transaction if there was an error if r := recover(); r != nil { tx.Rollback() } }() _, err = tx.Exec("INSERT INTO users (name) VALUES ('Alice')") if err != nil { // handle error and panic panic(err) } _, err = tx.Exec("INSERT INTO users (name) VALUES ('Bob'") if err != nil { // handle error and panic panic(err) } // Commit transaction err = tx.Commit() if err != nil { // handle error }In this example, we use a `defer` statement to automatically rollback the transaction if there was an error. We also use the `panic()` function to stop execution if an error occurs during the SQL statements. The `database/sql` package is built into Go and does not require any additional libraries.