数据库/ sql程序包会自动为您管理连接池。
sql.Open(..)返回 代表连接池 而不是单个连接的句柄。如果池中的所有连接都忙,则数据库/ sql软件包会自动打开一个新连接。
将其应用于代码意味着,您只需要共享db-handle并在HTTP处理程序中使用它:
package mainimport ( "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 handlerfunc 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) }}


