英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论