To work with database transactions and rollbacks in Go, you need to follow these general steps:
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.
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
*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
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.