Sobes.tech
Junior — Middle

How to implement transaction management in a system?

sobes.tech AI

Answer from AI

In Go, transaction management is usually implemented using the Begin(), Commit(), and Rollback() methods from the database/sql package. A transaction is first created with db.Begin(), then the necessary operations are performed, and finally, the transaction is either committed (Commit()) or rolled back (Rollback()) in case of an error.

Example:

trx, err := db.Begin()
if err != nil {
    // handle error
}

_, err = trx.Exec("INSERT INTO users(name) VALUES(?)", "Alice")
if err != nil {
    trx.Rollback()
    // handle error
}

err = trx.Commit()
if err != nil {
    // handle error
}

This approach guarantees the atomicity of operations and allows controlling data integrity.

How to implement transaction management in a system… - sobes.tech