如何在main函数中初始化mysql并将其放在另一个函数中?或者在其他地方初始化连接并在任何地方使用它?
下面有这样的事情(这个例子错了!)
package main
import (
"fmt"
"net/http"
_ "github.com/go-sql-driver/mysql"
"database/sql"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
stmt, err := db.Prepare("INSERT userinfo SET username=?,departname=?,created=?")
res, err := stmt.Exec("test", "test", "test")
}
func main() {
db, err := sql.Open("mysql", "connection")
if err != nil {
panic(err)
}
http.HandleFunc("/", indexHandler)
http.ListenAndServe(":3000", nil)
}
非常感谢!
答案 0 :(得分:3)
让它全球化:
var db *sql.DB
func indexHandler(w http.ResponseWriter, r *http.Request) {
stmt, err := db.Prepare(...
...
}
func main() {
var err error
db, err = sql.Open("mysql", "connection")
...
或创建处理程序作为闭包:
func createIndexHandler(db *sql.DB) (func (http.ResponseWriter, *http.Request)) {
return func(w http.ResponseWriter, r *http.Request) {
stmt, err := db.Prepare(...
...
}
}
func main() {
db, err := sql.Open("mysql", "connection")
...
http.HandleFunc("/", createIndexHandler(db))