0

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?

ceth
  • 44,198
  • 62
  • 180
  • 289
  • 2
    Never use relative import paths like `"../stackoverflow"`, always use the full import path for all imports. – JimB Feb 10 '17 at 13:56
  • 1
    The sqlx docs state that `sqlx.Open` follows the same semantics as [`sql.Open`](https://golang.org/pkg/database/sql/#Open). – JimB Feb 10 '17 at 13:58

0 Answers0