在另一个函数中使用 SQL 连接。

huangapple go评论94阅读模式
英文:

Use sql connection in another func

问题

在主函数中如何初始化MySQL连接并在另一个函数中使用?或者在另一个地方初始化连接并在任何地方使用?

类似下面的示例(此示例有误!)

package main

import (
	"fmt"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
	"database/sql"
)

var db *sql.DB

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() {
	var err error
	db, err = sql.Open("mysql", "connection")
	if err != nil {
		panic(err)
	}
	http.HandleFunc("/", indexHandler)
	http.ListenAndServe(":3000", nil)
}

无论如何,谢谢!

英文:

How init mysql connection in main function and place it another function? Or init connection in another place and use it anywhere?

Something like this below(this example wrong!)

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

Thanks anyway!

答案1

得分: 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))
}
英文:

Make it global:

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")
    ...

or create handler as closure:

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

huangapple
  • 本文由 发表于 2015年7月28日 18:09:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/31673269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定