Middle
Mis on tehing?
sobes.tech AI
Vastus AI-lt
A transaction is a sequence of operations that are executed as a single unit. In the context of databases, a transaction guarantees that all operations within it are completed successfully together, or in case of an error, they are rolled back to leave the system in a consistent state. In Go, transactions are often used with databases via the database/sql package.
Example of using a transaction in Go:
// db — *sql.DB object
ctx := context.Background()
tx, err := db.BeginTx(ctx, nil)
if err != nil {
log.Fatal(err)
}
_, err = tx.ExecContext(ctx, "INSERT INTO users(name) VALUES(?)", "Alice")
if err != nil {
tx.Rollback()
log.Fatal(err)
}
err = tx.Commit()
if err != nil {
log.Fatal(err)
}
Here, insert operations are performed within a transaction, which is either committed or rolled back in case of an error.