tx, err := db.Begin() if err != nil { log.Fatal(err) } defer tx.Rollback() _, err = tx.Exec("INSERT INTO customers (name, email) VALUES (?, ?)", "John Doe", "[email protected]") if err != nil { log.Fatal(err) } err = tx.Commit() if err != nil { log.Fatal(err) }
func TransferFunds(db *sql.DB, fromAccountID, toAccountID, amount int) error { tx, err := db.Begin() if err != nil { return err } defer func() { if err != nil { tx.Rollback() return } err = tx.Commit() }() // Begin transfer logic... }In this example, a function called "TransferFunds" is defined, which takes a database connection, two account IDs and an amount to transfer. Inside the function, a transaction is started using the "Begin" method on the connection. If an error occurs, the function immediately returns without committing any changes. If no errors occur, the function continues with the transfer logic, making the appropriate updates to the database. Finally, the changes are committed using the "Commit" method. If an error occurs during the commit, the transaction is rolled back using the "Rollback" method.