A
A
Arseny Sokolov2016-03-12 10:06:51
go
Arseny Sokolov, 2016-03-12 10:06:51

How to declare the err variable in Go when calling sql.Open if the db variable is global?

Here's how to track connection errors in such a situation?

var db *sql.DB

func connectDB() {
    db, _ = sql.Open("mysql", "[email protected]/dbname")
}

If the db variable is not declared in advance, then everything is clear, but how do they do it in this case?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Roman Kravchik, 2016-03-12
@ArsenBespalov

var db *sql.DB

func connectDB() {
    var err error
    db, err = sql.Open("mysql", "[email protected]/dbname")
}

and with processing:
var db *sql.DB

func connectDB() error {
    var err error
    if db, err = sql.Open("mysql", "[email protected]/dbname"); err != nil {
        return err
    }

or like this:
var db *sql.DB

func connectDB() (err error) {
    db, err = sql.Open("mysql", "[email protected]/dbname")
    return
}

H
huhrmuhr, 2016-03-12
@huhrmuhr

She is a link. Reassignment is not a problem.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question