douqin1932 2018-03-21 13:02
浏览 41
已采纳

将查询移至处理程序将获得“未定义:db”(golang)

I am trying to use Golang as a REST API. I have managed to get handlers to work and queries as well. But not got a query inside a handler to work.

When the query resides within the main() it works:

func handleRequests() {
    http.HandleFunc("/getuser", Getuser)
}

---> this handler gets respons on localhost:8080/getuser

func Getuser(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Getuser")
}

func main() {
    handleRequests()

    //Connect to db

    rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`)
    for rows.Next() {
        results := make(map[string]interface{})
        err = rows.MapScan(results)
    fmt.Printf("%#v
", results)
    }

    log.Fatal(http.ListenAndServe(":8080", nil))
}

But when I move the query to the handler it gives an error that the db is not defined.

func handleRequests() {
    http.HandleFunc("/getuser", Getuser)
}

---> this gives the error that the db is not defined

func Getuser(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`)
    for rows.Next() {
        results := make(map[string]interface{})
        err = rows.MapScan(results)
    fmt.Printf("%#v
", results)
    }
}

func main() {
    handleRequests()

    //Connect to db

    log.Fatal(http.ListenAndServe(":8080", nil))
 }

EDIT

Full code inside the handler (added db var as suggested), but gives various errors on "err".

 var db *sqlx.DB <---solved the db problem

 func Getsign(w http.ResponseWriter, r *http.Request) {
    rows, err := db.Queryx(`SELECT "USER_ID","USER_NAME" FROM user`)
    for rows.Next() {
        results := make(map[string]interface{})
        err = rows.MapScan(results)
        fmt.Printf("%#v
", results)
    }

    defer rows.Close()

    if err := rows.Err(); err != nil {
        log.Fatal(err)
    }
}

Any tip what I am doing wrong?

  • 写回答

2条回答 默认 最新

  • douba2011 2018-03-21 13:24
    关注

    Define your db variable outside of main, e.g.:

    var db *sql.DB
    
    func handler(w http.ResponseWriter, r *http.Request) {
        rows, err := db.Query(...)
        // use it
    }
    
    func main() {
        db, _ = sql.Open(...)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料