如何从另一个文件或包中导入gorm db连接 [英] how to import gorm db connection from another file or package
本文介绍了如何从另一个文件或包中导入gorm db连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习go,最近又学习了如何利用gorm连接到数据库.我不知道如何导入所说的连接.仅在 func main()
I'm learning go and I've recently learned how to leverage gorm to connect to a database. I can't figure out how to import said connection. Only open and defer it's closing in the scope of the func main()
我目前所拥有的:
func main(){
db, _ := gorm.Open("postgres", "host=localhost port=5432 user=someUser dbname=someDB password=somePW sslmode=disable")
defer db.Close()
}
这工作正常,我可以创建表并执行CRUD ...,但是所有操作都在main函数中.
This works fine and I can create tables and do CRUD ... but all in the main function.
无论如何,我可以做这样的事情(它不起作用)并在main中使用它:
Is there anyway I can do something like this(it didn't work) and use it in main:
func db(){
db, _ := gorm.Open("postgres", "host=localhost port=5432 user=someUser dbname=someDB password=somePW sslmode=disable")
defer db.Close()
return db
}
或者定义某种程序包,这也将允许我执行此操作.
Or define some kind of package that will also allow me to do this.
我知道db返回后,延迟基本上只会关闭连接,但是希望你们能得到我想要的.
I know that defer will basically just close the connect once db returns, but hopefully you guys get what I'm going for.
推荐答案
查看全文