tx, err := db.Begin() if err != nil { log.Fatal(err) } defer tx.Rollback() var name string err = tx.QueryRow("SELECT name FROM users WHERE id=?", userID).Scan(&name) if err != nil { log.Fatal(err) } fmt.Printf("User name: %s\n", name)
tx, err := db.Begin() if err != nil { log.Fatal(err) } defer tx.Rollback() stmt, err := tx.Prepare("INSERT INTO sales (customer_id, item, price) VALUES (?, ?, ?)") if err != nil { log.Fatal(err) } defer stmt.Close() res, err := stmt.Exec(customerID, itemName, price) if err != nil { log.Fatal(err) } salesID, err := res.LastInsertId() if err != nil { log.Fatal(err) } fmt.Printf("New sale ID: %d\n", salesID) err = tx.Commit() if err != nil { log.Fatal(err) }This code opens a database transaction, prepares an INSERT statement to add a new sales record to the "sales" table, executes the statement with the provided parameters, and retrieves the ID of the new record. It then prints the ID to the console. If there is an error executing the transaction, the code logs the error and rolls back the transaction. Otherwise, it commits the transaction to the database. The package library used in these examples is the standard Go database/sql package.