使用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.

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