How often should I call sql.Open in my program?

As the title says, I don't know if having a few instructions is sql.Opengood or bad, or what, or if I should have a file with only initialization, something like:

var db *sql.DB


func init() {
    var err error
    db, err = sql.Open
}

just wondering what the best practice will be. Thanks!

+4
source share
1 answer

You should at least check the error.
As stated in " Connecting to the Database ":

, Open : , . , , Ping:

if err := db.Ping(); err != nil {
  log.Fatal(err)
}

Close.

, .
. "Go/Golang sql.DB :

.
database/sql , , , .

elithrar , database.sql/#Open :

goroutines . , Open .
.

*sql.DB , SetMaxIdleConns ( ) SQL .

init, , main():

var db *sql.DB
func init() {
    db, err = sql.Open(DBparms....)
}

init() , , main , , init, .
init() , ( , , , ).

+4

Source: https://habr.com/ru/post/1614826/


All Articles