// Start a transaction and execute a query, with error handling tx, err := db.Beginx() if err != nil { log.Fatal(err) } var result int err = tx.Get(&result, "SELECT count(*) FROM users WHERE active = ?", true) if err != nil { tx.Rollback() log.Fatal(err) } // Use the result and commit the transaction if result > 0 { // ... } err = tx.Commit() if err != nil { log.Fatal(err) }
// Use a named parameter in a transaction tx, err := db.Beginx() if err != nil { log.Fatal(err) } _, err = tx.NamedExec("INSERT INTO users (name, age) VALUES (:name, :age)", map[string]interface{}{ "name": "Alice", "age": 27, }) if err != nil { tx.Rollback() log.Fatal(err) } err = tx.Commit() if err != nil { log.Fatal(err) }In this example, we use the `NamedExec()` method of the `Tx` struct to insert a new row into the `users` table. Note that we use named parameters (prefixed with a colon) to indicate the values that should be substituted in the SQL statement. Overall, the `github.com.jmoiron.sqlx` package is a powerful library that simplifies the process of working with SQL databases in Go, and the `Tx` struct is a key component that enables atomic transactions to be used.