6

In Go database/sql package it says it is rare to close the database with db.Close because it is meant to be shared by many go routines. Then which one is better when we are given 100 functions that queries from a same data:

  1. Open the database inside each function
  2. Open the database only one time and use the same connection for every 100 function.

1 is easier because if one fails other 99 can still be working. And no need to pass database connection arguments. But in performance wise which one is better?

2
  • 2. If the connection fails for one of the queries you open it again. Commented Dec 2, 2014 at 3:07
  • I know but ehich one is better? Opening sevral connection takes more resource? Commented Dec 2, 2014 at 3:15

1 Answer 1

12

You missed an important part of what the documentation says:

The returned DB is safe for concurrent use by multiple goroutines and maintains its own pool of idle connections. Thus, the Open function should be called just once. It is rarely necessary to close a DB.

(emphasis mine)

So, your option #2 doesn't actually make sense. The connections are pooled - so use the same connection for every 100 function doesn't apply. Also, option #1 is a waste of time - just do it once as the documentation states, but call Ping after you do just to make sure everything is fine (and have it actually attempt to connect to the database - regardless of driver).

Sign up to request clarification or add additional context in comments.

1 Comment

You are right. I neglected to see the Open, only looking at Close. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.