tx, err := db.Begin() if err != nil { log.Fatal(err) } _, err = tx.Exec("UPDATE users SET name = 'John Doe' WHERE id = 1") if err != nil { tx.Rollback() log.Fatal(err) } err = tx.Commit() if err != nil { log.Fatal(err) }
func transferMoney(tx *sql.Tx, from, to string, amount float64) error { // Debit the "from" account _, err := tx.Exec("UPDATE accounts SET balance = balance - ? WHERE name = ?", amount, from) if err != nil { return err } // Credit the "to" account _, err = tx.Exec("UPDATE accounts SET balance = balance + ? WHERE name = ?", amount, to) if err != nil { return err } return nil }In this example, a function called transferMoney is defined that debits a specified amount of money from one account and credits it to another account within a transaction. The function takes a pointer to a transaction, the name of the "from" and "to" accounts, and the amount to be transferred as arguments. The SQL queries are executed within the provided transaction using the Exec function. The function returns an error if any of the SQL queries fail.