Junior — Middle
Kuidas alustada uut tehingut andmebaasi haldussüsteemis?
sobes.tech AI
Vastus AI-lt
In Go, to work with transactions in databases, the database/sql package is commonly used. To initiate a new transaction, call the Begin() method on the *sql.DB object. This method returns a *sql.Tx object, representing the transaction. Afterwards, you can confirm or cancel the transaction using the Commit() or Rollback() methods.
Example:
import (
"database/sql"
_ "github.com/lib/pq" // PostgreSQL driver
)
func example(db *sql.DB) error {
tx, err := db.Begin()
if err != nil {
return err
}
// Execute operations within the transaction
_, err = tx.Exec("INSERT INTO users(name) VALUES($1)", "Alice")
if err != nil {
tx.Rollback() // cancel transaction on error
return err
}
return tx.Commit() // confirm transaction
}