文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
Databases
One of the most asked questions I get about web development in Go is how to connect to a SQL database. Thankfully, Go has a fantastic SQL package in the standard library that allows us to use a whole slew of drivers for different SQL databases. In this example we will connect to a SQLite database, but the syntax (minus some small SQL semantics) is the same for a MySQL or PostgreSQL database.
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
_ "github.com/mattn/go-sqlite3"
)
func main() {
db := NewDB()
log.Println("Listening on :8080")
http.ListenAndServe(":8080", ShowBooks(db))
}
func ShowBooks(db *sql.DB) http.Handler {
return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
var title, author string
err := db.QueryRow("select title, author from books").Scan(&title, &author)
if err != nil {
panic(err)
}
fmt.Fprintf(rw, "The first book is '%s' by '%s'", title, author)
})
}
func NewDB() *sql.DB {
db, err := sql.Open("sqlite3", "example.sqlite")
if err != nil {
panic(err)
}
_, err = db.Exec("create table if not exists books(title text, author text)")
if err != nil {
panic(err)
}
return db
}
Exercises
- Make use of the
Query
function on oursql.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论