Go/Golang sql.DB reuse in functions

前端 未结 2 1693
失恋的感觉
失恋的感觉 2021-02-14 14:59

sql.Open() returns a variable of type *sql.DB

I have a function that calls 10 other functions that all need to make database calls

Is it more correct/efficient t

2条回答
  •  爱一瞬间的悲伤
    2021-02-14 15:30

    Declare a var db *sql.DB globally, and then reuse it across your code. Here is an example (simplified):

    var db *sql.DB
    
    func DoLotsOfThings() {
        DoTask1(db)
        DoTask2(db)
    }
    
    func main() {
      db, _ = sql.Open() # or whatever you use
      defer db.Close()
      DoLotsOfThings()
    }
    

    Declaring *sql.DB globally also have some additional benefits such as SetMaxIdleConns (regulating connection pool size) or preparing SQL statements across your application.

提交回复
热议问题