donglian4770 2016-09-11 00:30
浏览 56
已采纳

使用MySQL数据库狂欢没有gorm

I've placed everything into app.go and the database opens correctly but Index cannot access the global variable. The global variable doesn't seem to be global because if I remove the use of Db after assigning it inside InitDB I get the error "Db declared and not used"

package controllers

import (
    "database/sql"
    "fmt"

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

var Db *sql.DB

type App struct {
    *revel.Controller
}

func (c App) Index() revel.Result {
    if c.Params.Get("id") == "3012" {

        return c.Redirect("http://youtube.com")
    }
    fmt.Println("here is the db from index:", Db)
    return c.Render()
}

func InitDB() {

    // open db
    Db, err := sql.Open("mysql", "username:xxxxxxx@tcp(xxxxxxx:3306)/xxxx")
    if err != nil {
        revel.INFO.Println("DB Error", err)
    }
    revel.INFO.Println("DB Connected")
    //fmt.Println(Db)

}

func init() {
    revel.OnAppStart(InitDB)
}

any help would be appreciated! Thanks.

  • 写回答

1条回答 默认 最新

  • dougou2937 2016-09-11 00:35
    关注

    You are declaring your variable in a wrong way. The current way you are using its like declaring a normal variable for the InitDB scope (you are using := ).

    func InitDB() {
    
        var err error
        Db, err = sql.Open("mysql", "username:xxxxxxx@tcp(xxxxxxx:3306)/xxxx")
        if err != nil {
            revel.INFO.Println("DB Error", err)
        }
        revel.INFO.Println("DB Connected")
        //fmt.Println(Db)
    
    }
    

    I also suggest creating a folder inside app called controllers to store all your route logic and if needed call the app.Db variable

    This should work

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
  • ¥50 STM32单片机传感器读取错误
  • ¥15 (关键词-阻抗匹配,HFSS,RFID标签天线)
  • ¥15 机器人轨迹规划相关问题
  • ¥15 word样式右侧翻页键消失