stmt, err := db.Prepare("SELECT name FROM users WHERE id = ?") if err != nil { // handle error } defer stmt.Close() rows, err := stmt.Query(42) if err != nil { // handle error } defer rows.Close() for rows.Next() { var name string err := rows.Scan(&name) if err != nil { // handle error } fmt.Println(name) }
stmt, err := db.Prepare("INSERT INTO users (name, email) VALUES (?, ?)") if err != nil { // handle error } defer stmt.Close() result, err := stmt.Exec("Alice", "[email protected]") if err != nil { // handle error } numRowsAffected, err := result.RowsAffected() if err != nil { // handle error } fmt.Println("Inserted", numRowsAffected, "rows")In this example, a `Stmt` is prepared with an insert query that has two parameters (name and email). Then, the statement is executed with specific values for the parameters (Alice and [email protected]), and the result is returned as an `sql.Result` object. Finally, the number of rows affected by the insert is printed. The `database/sql` package is a standard library in Go language, and it's used to interact with different types of databases by importing the relevant driver package for the specific database that we want to use.