Middle+
What is the syntax for transactions in Go/SQL?
sobes.tech AI
Answer from AI
In Go, the database/sql package is used for working with database transactions. The main steps:
- Begin a transaction with
db.Begin(). - Perform necessary operations through the transaction object
tx. - Commit the changes with
tx.Commit()or rollback withtx.Rollback().
Example:
import (
"database/sql"
_ "github.com/lib/pq" // PostgreSQL driver
)
func doTransaction(db *sql.DB) error {
tx, err := db.Begin()
if err != nil {
return err
}
_, err = tx.Exec("INSERT INTO users(name) VALUES($1)", "Alice")
if err != nil {
tx.Rollback()
return err
}
_, err = tx.Exec("UPDATE accounts SET balance = balance - 100 WHERE user_id = $1", 1)
if err != nil {
tx.Rollback()
return err
}
return tx.Commit()
}
It is always important to handle errors and call Rollback on errors to avoid leaving the transaction open.