Sobes.tech
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:

  1. Begin a transaction with db.Begin().
  2. Perform necessary operations through the transaction object tx.
  3. Commit the changes with tx.Commit() or rollback with tx.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.