2015-07-28 49 views
1

如何在主函數中初始化mysql連接並將它放在另一個函數中?或在另一個地方初始化連接,並在任何地方使用?在另一個函數中使用sql連接

像這樣的東西如下(本例中錯誤的!)

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) 
} 

還是要謝謝你!

回答

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)) 
+0

謝謝配合! – Liamka

相關問題