How to work with database transactions and rollbacks in Go?

To work with database transactions and rollbacks in Go, you need to follow these general steps:

  1. Connect to the database: Use a Go database library like database/sql to establish a connection with your database. Import the relevant database driver and open a connection.
import ( "database/sql" _ "database/sql/driver" // Import the database driver package ) db, err := sql.Open("<driver>", "<connection string>") // Open a connection if err != nil { // Handle error } defer db.Close() // Close the connection when you're done

Make sure to replace <driver> with the appropriate database driver (e.g., mysql, postgres, etc.), and <connection string> with the connection details specific to your database.

  1. Start a transaction: Use the Begin method of the *sql.DB object to start a new transaction.
tx, err := db.Begin() if err != nil { // Handle error } defer tx.Rollback() // Defer rollback in case of error
  1. Execute database operations: Use the transaction object (*sql.Tx) to execute your database queries or modifications. Use the Exec, Query, or other appropriate methods provided by the database library.
// Example of an INSERT statement _, err = tx.Exec("INSERT INTO tablename (column1, column2) VALUES (?, ?)", value1, value2) if err != nil { // Handle error tx.Rollback() // Rollback the transaction } // Execute more queries/modifications if needed
  1. Commit or rollback the transaction: After executing all the necessary database operations, decide whether to commit or rollback the transaction based on the success or failure of your operations.
err = tx.Commit() // Commit the changes if err != nil { // Handle error tx.Rollback() // Rollback if commit fails }

If you encounter an error at any point within the transaction, you can directly call Rollback to discard all changes and revert to the previous state. Similarly, if you want to manually rollback the transaction without committing, you can call Rollback explicitly.

By following these steps, you can effectively work with database transactions and rollbacks in Go.