英文:
using mysql db for revel without gorm
问题
我已经将所有内容放入了app.go文件中,数据库正确打开,但是Index函数无法访问全局变量。全局变量似乎不是全局的,因为如果我在InitDB函数内部分配完后删除对Db的使用,就会出现"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)
}
希望能帮到你!谢谢。
英文:
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
得分: 1
你正在错误地声明变量。你当前的方式就像在InitDB作用域中声明一个普通变量一样(你使用了:=)。
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)
}
我还建议在app文件夹内创建一个名为controllers的文件夹,用于存储所有的路由逻辑,并在需要时调用app.Db变量。
这样应该可以工作。
英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论