Here is my code:
package db_layer
import (
"github.com/jmoiron/sqlx"
"log"
"../stackoverflow"
)
var db *sqlx.DB
func Insert_so_Questions(questions []stackoverflow.SOQuestion) {
var err error
db, err = sqlx.Open("postgres", "user=demas password=root host=192.168.1.71 port=5432 dbname=news sslmode=disable")
if err != nil {
log.Fatal(err)
}
defer db.Close()
tx := db.MustBegin()
for _, q := range questions {
tx.MustExec("INSERT INTO stackquestions(title, link) VALUES($1, $2)", q.Title, q.Link)
}
tx.Commit()
}
Everytime I call the function from other modules I open connection. What is the good way to keep connection open between the function calls?
I think about pass connection to every function which is working with DB, but may be there is a better way?