全局变量 out out init.go 中的 in revel

huangapple go评论85阅读模式
英文:

global var out out init.go in revel

问题

controllers/app.go中,你可以通过app.DB来访问全局变量DB。在Index方法中,你可以使用app.DB执行数据库查询操作,例如执行SELECT * FROM test_table语句。请注意,你需要确保在调用app.DB之前已经调用了InitDB方法来初始化数据库连接。

英文:

(EDITING to fix capitalization and add context)

In revel's init.go, I have a global var: DB.

package app

import (
 "database/sql"
 "fmt"

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

func InitDB() {
 
 connstring := fmt.Sprintf("revel:revel@tcp(localhost:3336)/revel")

 var err error
 DB, err = sql.Open("mysql", connstring)
 if err != nil {
	revel.INFO.Println("DB Error", err)
 }

}

How do I get that db variable in the rest of the app? Specifically, I was going to use this var in the models.

To start, how would I get it to work in this controller?
controllers/app.go

package controller

func (c App) Index() revel.Result {
 rows, err := app.DB.Exec("SELECT * FROM test_table")
 //do something with rows
 return c.Render()
}

答案1

得分: 1

Revel让你可以自己创建数据库,所以你可以自由选择在哪里建立连接以及如何实现连接。

你的InitDB()函数必须设置一个公共变量,例如DB(意味着它的名称是大写的),然后你可以通过它所在的包来访问它。

所以请注意,你的app/init.go文件位于app包内:

package app

var DB *sql.DB

func InitDB() { DB = .... }

在Go语言中,当你的应用程序运行时,每个包都充当一种"单例",这意味着在应用程序的任何其他地方访问:

app.DB

这将在app包中查找名为DB的变量。如果你已经运行了InitDB()函数来连接数据库,那么app.DB将允许所有其他包使用该数据库。

英文:

Revel makes you "roll your own db" so it's up to you where connections are made and how to implement them.

Your InitDB() function must setup a public variable, e.g. DB (meaning its name is capitalized) which you will then access via the package that it lives in.

So notice your app/init.go is inside of package app:

package app

var DB *sql.DB

func InitDB() { DB = .... }

In Go, when your application is running each package acts as a sort of "singleton" so that anywhere else in the application where you access:

app.DB

This will look for the variable called DB in the app package. And if you have already run InitDB() to connect to the database, then app.DB will allow all other packages to use the database.

huangapple
  • 本文由 发表于 2016年3月7日 09:04:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/35834645.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定