Go / Golang sql.DB reuse in functions

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

I have a function that calls 10 other functions that everyone should perform for database calls

Is it more correct / efficient:

  • Send a * sql.DB pointer to each function or
  • Create a new * sql.DB object in each function

Value

func DoLotsOfThings() { db, _ := sql.Open() defer db.Close() DoTask1(db) DoTask2(db) } 

or

 func DoLotsOfThings() { DoTask1() DoTask2() } func DoTask1() { db, _ := sql.Open() defer db.Close() } func DoTask1() { db, _ := sql.Open() defer db.Close() } 

The reason I'm asking is because I am currently sending a pointer to each function and my driver seems to break. I use http://code.google.com/p/odbc , which makes me believe that each function should have its own, and that I can rely on the driver internals.

EDIT

Damage to the RE driver occurs only in conditions of high traffic intensity. And this only happens after they say ten minutes or so. This makes me think that there is some kind of memory leak due to which the use of the driver stops working. However, I put off db.Close () for each * sql.DB instance, so I don't know what else I can do to solve this problem.

andybalholm says that pooling is handled internally, which seems accurate because it only breaks after I try to execute something, and not when I call sql.Open ()

If I leave the Go Go application running, it will not be able to execute any SQL queries, but if I try to run other Go tests that connect to MSSQL separately and run the queries, it works.

+8
go odbc freetds unixodbc
source share
2 answers

You do not need to open database connections everywhere. The database / sql package makes the connection a pool inside, opening and closing connections as needed, providing the illusion of a single connection that can be used at a time.

You may need to look elsewhere for the cause of your driver’s damage. More information on this will allow people to understand what is happening.

+6
source share

Declare var db *sql.DB globally and then reuse it in 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() } 

The *sql.DB globally also has some additional benefits, such as SetMaxIdleConns (throttling connection pool size) or preparing SQL statements in your application.

+18
source share

All Articles