How can I share database connection between packages in Go?

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

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.

huangapple
  • 本文由 发表于 2015年2月27日 03:45:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/28751402.html
匿名

发表评论

匿名网友

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

确定