我是Go noob,找不到任何在Go中打开mysql连接然后在http处理程序之间共享它的完整示例。这是我的代码到目前为止,我将如何使用我在HomeHandler中的main()中打开的数据库连接?
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/gorilla/mux"
"log"
"net/http"
)
func main() {
fmt.Println("starting up")
db, err := sql.Open("mysql", "root:@/mydb?charset=utf8")
if err != nil {
log.Fatalf("Error opening database: %v", err)
}
db.SetMaxIdleConns(100)
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "home")
}
答案 0 :(得分:59)
database / sql包会自动为您管理连接池。
sql.Open(..)
返回表示连接池的句柄,而不是单个连接。如果池中的所有连接都忙,则database / sql包会自动打开新连接。
应用于您的代码,这意味着您只需要共享db-handle并在HTTP处理程序中使用它:
package main
import (
"database/sql"
"fmt"
"github.com/gorilla/mux"
_ "github.com/go-sql-driver/mysql"
"log"
"net/http"
)
var db *sql.DB // global variable to share it between main and the HTTP handler
func main() {
fmt.Println("starting up")
var err error
db, err = sql.Open("mysql", "root@unix(/tmp/mysql.sock)/mydb") // this does not really open a new connection
if err != nil {
log.Fatalf("Error on initializing database connection: %s", err.Error())
}
db.SetMaxIdleConns(100)
err = db.Ping() // This DOES open a connection if necessary. This makes sure the database is accessible
if err != nil {
log.Fatalf("Error on opening database connection: %s", err.Error())
}
r := mux.NewRouter()
r.HandleFunc("/", HomeHandler)
http.Handle("/", r)
http.ListenAndServe(":8080", nil)
}
func HomeHandler(w http.ResponseWriter, r *http.Request) {
var msg string
err := db.QueryRow("SELECT msg FROM hello WHERE page=?", "home").Scan(&msg)
if err != nil {
fmt.Fprintf(w, "Database Error!")
} else {
fmt.Fprintf(w, msg)
}
}