How to Use Transactions in Go with database/sql

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()