初始化数据库为全局变量

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

Initialize database as global variable

问题

将数据库初始化为全局变量是一个好主意吗?它能够工作吗?

我在考虑以下的代码:

func MustDB(d *sql.DB, err error) *sql.DB {
   if err != nil {
     log.Panic(err)
   }
   return d
}

// 我不知道的是如何调用db.Close()
// 用户名和密码也可以类似的方式读取
var db *DB = MustDB(db.Open(...))

func MustPrepare(db *sql.DB, query string) *sql.Stmt {
  res, err := sql.Prepare(db, query)
  if err!=nil {
    log.Panic(err)
  }
  return ret;
}

优点是,我可以将预编译的 SQL 语句作为全局变量简单地创建。我不需要创建和管理一个存储,将所有的 SQL 命令放在其中。我只需要编写:

var s1 *sql.Stmt = MustPrepare(db, "SELECT * FROM MyTable")
var s2 *sql.Stmt = MustPrepare(db, "INSERT INTO MyTable(col1, col2) VALUES(?,?)")
var s3 *sql.Stmt = MustPrepare(db, "DELETE FROM MyTable WHERE col1=?")

你认为这种模式有用,还是根本无法工作?

英文:

Is it a good idea to initialize databaze as global variable? Can it work?

I'm thinking about something like that:

func MustDB(d *sql.DB, err error) *sql.DB {
   if err != nil {
     log.Panic(err)
   }
   return d
}

// what I don't know - is how to call db.Close()
// username and password can also be read similar way
var db *DB = MustDB(db.Open(...))

func MustPrepare(db *sql.DB, query string) *sql.Stmt {
  res, err := sql.Prepare(db, query)
  if err!=nil {
    log.Panic(err)
  }
  return ret;
}

The advantage is, I can simple create prepared sql statements as global variables. I don't have to create and manage a storage, where all sql commands will be put. Only I write:

var s1 *sql.Stmt = MustPrepare(db, "SELECT * FROM MyTable")
var s2 *sql.Stmt = MustPrepare(db, "INSERT INTO MyTable(col1, col2) VALUES(?,?)")
var s3 *sql.Stmt = MustPrepare(db, "DELETE FROM MyTable WHERE col1=?")

Do you think, that pattern is usefull, or it cannot work at all.

答案1

得分: 3

在Go语言中,通常使用Open函数(至少在数据库访问包中是全局的)来初始化一个全局的*DB结构体。这并不会打开一个实际的数据库连接,而是创建一个连接池。因此,应该只有一个实例。你可以在包的init函数中进行初始化。

参考以下链接获取一个很好的入门指南:
http://go-database-sql.org/
或者
https://www.vividcortex.com/blog/2015/01/14/the-ultimate-guide-to-building-database-driven-apps-with-go/

英文:

In go you typicallly initialize a global *DB struct using Open (at least global in your Database Access package). That does not open an actual connection to the DB, but creates a connection pool. Therefore there should be only one instance of it. You can initialize that in init of your package.

See
http://go-database-sql.org/
or
https://www.vividcortex.com/blog/2015/01/14/the-ultimate-guide-to-building-database-driven-apps-with-go/
for a good introductory guide.

答案2

得分: 0

是的,这是一个很好的方法。当你阅读Go文档时,它明确告诉你:

关闭DB是很少见的,因为DB句柄应该是长期存在的,并在许多Go协程之间共享。

Go会维护自己的空闲连接池。因此,应该只调用一次Open函数。很少需要关闭DB。

英文:

Yes it is a good approach. when you go through the go documentation it clearly tells you

> It is rare to Close a DB, as the DB handle is meant to be long-lived
> and shared between many go routines.

Go maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

答案3

得分: -2

作为一个经验法则,我认为这种使用数据库连接的方式并不是一个好的实践,你应该将其私有化,并在需要时打开/关闭它 初始化数据库为全局变量

但是如果它能够正常工作并且你喜欢这种方式,那么就没有什么问题。

英文:

As a rule of thumb I don't think its good practice to use database connections this way, you should privatize it and just open/close as you need it 初始化数据库为全局变量

But if it works and you like it then nothings wrong with doing it that way.

huangapple
  • 本文由 发表于 2015年10月23日 16:33:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/33298030.html
匿名

发表评论

匿名网友

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

确定