txn := client.NewTxn(context.Background(), conn)
rows, err := txn.Query("SELECT * FROM users") if err != nil { txn.Rollback() log.Fatalf("Failed to read data: %v", err) } defer rows.Close() for rows.Next() { var id int var name string if err := rows.Scan(&id, &name); err != nil { log.Fatalf("Failed to read row: %v", err) } fmt.Printf("User #%d: %s\n", id, name) }
_, err := txn.Exec("INSERT INTO users (name) VALUES ($1)", "Alice") if err != nil { txn.Rollback() log.Fatalf("Failed to write data: %v", err) }In this code snippet, we execute an INSERT query within the transaction to add a new user to the "users" table. If any errors occur, we roll back the transaction and log the error. Overall, the "github.com/cockroachdb/cockroach/client" package provides a powerful toolset for building distributed SQL databases. The Txn struct is just one of many features included in the library.