英文:
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))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论