Junior — Middle
How can changes be rolled back within a single transaction?
sobes.tech AI
Answer from AI
In Go, the database/sql package is typically used for working with transactions. To roll back changes within a transaction, you need to call the Rollback() method on the transaction object. This is usually done in case of an error to cancel all changes made within the transaction.
Example:
trx, err := db.Begin()
if err != nil {
// handle error
}
// Perform operations within the transaction
_, err = trx.Exec("INSERT INTO users(name) VALUES(?)", "John")
if err != nil {
trx.Rollback() // rollback transaction on error
return err
}
// If everything is successful, commit the transaction
err = trx.Commit()
if err != nil {
return err
}
Thus, calling trx.Rollback() cancels all changes made within the current transaction.