Database 如何在Go中的包之间共享数据库连接?
我在我的Database 如何在Go中的包之间共享数据库连接?,database,go,Database,Go,我在我的main包中声明我的数据库连接,有点像这样: package main var Db *sql.DB func main() { var err error db, err = sql.Open("postgres", "stuff...") // error handling and more app stuff } 首先,我的所有代码都在main包中,我可以从其他文件访问数据库连接。但是,我想将代码分成包,现在Db变量不再可见 是否可以跨软件包共享它,
main
包中声明我的数据库连接,有点像这样:
package main
var Db *sql.DB
func main() {
var err error
db, err = sql.Open("postgres", "stuff...")
// error handling and more app stuff
}
首先,我的所有代码都在main
包中,我可以从其他文件访问数据库连接。但是,我想将代码分成包,现在Db
变量不再可见
是否可以跨软件包共享它,或者我必须将它作为参数添加到我在
main
函数中对其他软件包的任何调用中?我将在我的一个应用程序中共享当前的一些代码
首先
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
// Some other set up here
}
最后
package main
import (
"conf"
"model"
)
func main() {
db := conf.ConnectDB()
model.SetDatabase(db)
// Some other stuff
}
希望这有帮助。我将分享我的一个应用程序中当前的一些代码 首先
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
// Some other set up here
}
最后
package main
import (
"conf"
"model"
)
func main() {
db := conf.ConnectDB()
model.SetDatabase(db)
// Some other stuff
}
希望这有帮助。我将分享我的一个应用程序中当前的一些代码 首先
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
// Some other set up here
}
最后
package main
import (
"conf"
"model"
)
func main() {
db := conf.ConnectDB()
model.SetDatabase(db)
// Some other stuff
}
希望这有帮助。我将分享我的一个应用程序中当前的一些代码 首先
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
// Some other set up here
}
最后
package main
import (
"conf"
"model"
)
func main() {
db := conf.ConnectDB()
model.SetDatabase(db)
// Some other stuff
}
希望这有帮助。可以从某个包(例如
DBConn
或类似的包)导出变量,或者根据需要将其传递到子包中。就像处理任何其他信息一样。可以从某个包(例如DBConn
或类似的包)导出变量,也可以根据需要将其传递到子包中。就像处理任何其他信息一样。可以从某个包(例如DBConn
或类似的包)导出变量,也可以根据需要将其传递到子包中。就像处理任何其他信息一样。可以从某个包(例如DBConn
或类似的包)导出变量,也可以根据需要将其传递到子包中。就像你对任何其他信息所做的一样。尽管这个答案很好用,但我最终使用的是面向http且更适合我的应用程序的方法(而且根本不使用全局)。更好的方法。尽管这个答案很好用,但我最终使用的是面向http且更适合我的应用程序的方法(而且根本不使用全局变量)。更好的方法。尽管这个答案非常好用,但我最终还是使用了面向http且更适合我的应用程序的方法(而且根本不使用全局变量)。更好的方法。尽管这个答案非常好用,但我最终还是使用了面向http且更适合我的应用程序的方法(而且根本不使用globals)更好的方法。