Start a transaction with db.BeginTx, execute queries on the Tx object, and finalize with Commit or Rollback.
Use db.BeginTx() to start a transaction, execute your queries on the returned *sql.Tx, and call Commit() or Rollback() to finalize.
ctx := context.Background()
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
_, err = tx.ExecContext(ctx, "INSERT INTO users (name) VALUES (?)", "Alice")
if err != nil {
return err
}
return tx.Commit()
A transaction groups multiple database changes into a single unit that either all succeed or all fail. It prevents data corruption if an error happens halfway through a process. Think of it like a bank transfer where money is only removed from one account if it successfully arrives in the other.