Go/Golang sql.DB reuse in functions

前端 未结 2 1692
失恋的感觉
失恋的感觉 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.

    0 讨论(0)
  • 2021-02-14 15:39

    You shouldn't need to open database connections all over the place. The database/sql package does connection pooling internally, opening and closing connections as needed, while providing the illusion of a single connection that can be used concurrently.

    Probably you need to look elsewhere for the cause of your driver breakage. Some more details about that would make it easier for people to figure out what is going on.

    0 讨论(0)
提交回复
热议问题