How to work with transactions in Go to ensure data consistency in SQL databases?

To work with transactions in Go for ensuring data consistency in SQL databases, you can follow these steps:

  1. Import the necessary Go packages:
import ( "database/sql" "log" _ "github.com/go-sql-driver/mysql" // Import the SQL driver for the specific database you are using )
  1. Establish a connection with your SQL database:
db, err := sql.Open("mysql", "username:password@tcp(your-database-host:port)/database-name") if err != nil { log.Fatal(err) } defer db.Close()
  1. Begin a transaction:
tx, err := db.Begin() if err != nil { log.Fatal(err) } defer tx.Rollback()
  1. Execute your SQL statements inside the transaction. Use tx.Exec() for insert, update, and delete operations, or tx.Query() and tx.QueryRow() for select operations.
_, err = tx.Exec("INSERT INTO table_name (column1, column2) VALUES (?, ?)", value1, value2) if err != nil { log.Fatal(err) }
  1. Commit the transaction if all statements executed successfully:
err = tx.Commit() if err != nil { log.Fatal(err) }
  1. Handle any potential errors and roll back the transaction if necessary:
if err != nil { log.Fatal(err) err = tx.Rollback() if err != nil { log.Fatal(err) } }

By following these steps, you can ensure data consistency by either committing all database changes made within a transaction or rolling back the changes if any error occurs.