Databases

One of the most asked questions I get about web development in Go is how toconnect to a SQL database. Thankfully, Go has a fantastic SQL package in thestandard library that allows us to use a whole slew of drivers for differentSQL databases. In this example we will connect to a SQLite database, but thesyntax (minus some small SQL semantics) is the same for a MySQL or PostgreSQLdatabase.

  1. package main
  2. import (
  3. "database/sql"
  4. "fmt"
  5. "log"
  6. "net/http"
  7. _ "github.com/mattn/go-sqlite3"
  8. )
  9. func main() {
  10. db := NewDB()
  11. log.Println("Listening on :8080")
  12. http.ListenAndServe(":8080", ShowBooks(db))
  13. }
  14. func ShowBooks(db *sql.DB) http.Handler {
  15. return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
  16. var title, author string
  17. err := db.QueryRow("select title, author from books").Scan(&title, &author)
  18. if err != nil {
  19. panic(err)
  20. }
  21. fmt.Fprintf(rw, "The first book is '%s' by '%s'", title, author)
  22. })
  23. }
  24. func NewDB() *sql.DB {
  25. db, err := sql.Open("sqlite3", "example.sqlite")
  26. if err != nil {
  27. panic(err)
  28. }
  29. _, err = db.Exec("create table if not exists books(title text, author text)")
  30. if err != nil {
  31. panic(err)
  32. }
  33. return db
  34. }

Exercises

  • Make use of the Query function on our sql.DB instance to extract a collection of rows and map them to structs.
  • Add the ability to insert new records into our database by using an HTML form.
  • go get github.com/jmoiron/sqlx and observe the improvements made over the existing database/sql package in the standard library.

原文: https://codegangsta.gitbooks.io/building-web-apps-with-go/content/databases/index.html