英文:
How can I share database connection between packages in Go?
问题
我在main
包中声明了我的数据库连接,就像这样:
package main
import "database/sql"
var Db *sql.DB
func main() {
var err error
Db, err = sql.Open("postgres", "stuff...")
// 错误处理和其他应用程序逻辑
}
起初,我把所有的代码都放在main
包中,可以从其他文件中访问数据库连接。然而,我想将代码分离到不同的包中,现在Db
变量不再可见了。
是否可以在不同的包之间共享它,或者我必须将它作为参数添加到我在main
函数中调用其他包的地方?
英文:
I declare my database connection in my main
package, sort of like this:
package main
var Db *sql.DB
func main() {
var err error
db, err = sql.Open("postgres", "stuff...")
// error handling and more app stuff
}
To begin with I had all of my code in the main
package and I could access the database connection from other files. However, I want to separate code into packages, and now the Db
variable isn't visible anymore.
Is it possible to share it across packages or do I have to add it as a parameter to whatever calls to other packages I have in my main
function?
答案1
得分: 4
我将分享一段目前在我的应用程序中的代码。
首先...
package conf
import (
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
func ConnectDB() *gorm.DB {
db, err := gorm.Open("postgres", /**/)
if err != nil {
panic(err)
}
db.LogMode(true)
return &db
}
然后...
package model
import (
"github.com/jinzhu/gorm"
)
var DB *gorm.DB
func SetDatabase(db *gorm.DB) {
DB = db
// 这里还有其他设置
}
最后...
package main
import (
"conf"
"model"
)
func main() {
db := conf.ConnectDB()
model.SetDatabase(db)
// 这里还有其他内容
}
希望这能有所帮助。
英文:
I'll share a bit of code currently in one of my apps.
First...
package conf
import (
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
)
func ConnectDB() *gorm.DB {
db, err := gorm.Open("postgres", /**/)
if err!=nil {
panic(err)
}
db.LogMode(true)
return &db
}
Then....
package model
import (
"github.com/jinzhu/gorm"
)
var DB *gorm.DB
func SetDatabase(db *gorm.DB) {
DB = db
// Some other set up here
}
Finally...
package main
import (
"conf"
"model"
)
func main() {
db := conf.ConnectDB()
model.SetDatabase(db)
// Some other stuff
}
Hope this helps.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论