shad-go/lectures/07-sql/tx/tx.go

25 lines
378 B
Go
Raw Normal View History

2020-04-09 11:15:34 +00:00
package tx
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
import (
"context"
"database/sql"
"log"
)
func Begin(ctx context.Context, db *sql.DB) {
tx, err := db.BeginTx(ctx, nil)
if err != nil {
log.Fatal(err)
}
defer tx.Rollback()
2021-04-08 11:37:21 +00:00
_, err = tx.ExecContext(ctx, `UPDATE users SET name = "Tyador Borlú" WHERE id = 1`)
if err != nil {
2020-04-09 11:15:34 +00:00
log.Fatal(err)
}
2020-04-08 19:20:23 +00:00
2020-04-09 11:15:34 +00:00
if err = tx.Commit(); err != nil {
log.Fatal(err)
}
2020-04-08 19:20:23 +00:00
}