Reputation: 1233
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.
Upvotes: 1
Views: 773
Reputation: 2280
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.
Upvotes: 0
Reputation: 1463
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.
Upvotes: 3
Reputation: 27
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.
Upvotes: -2