S.Kiran
S.Kiran

Reputation: 17

How do I call variable in sql.open function of golang

How do I achieve replacing of the practice of calling actual password in above code with a variable.

pwd := "password"
    db, err := sql.Open("mysql", "root:pwd@/events")
if err != nil {
    fmt.Printf("Error: Failed to connect events schema. \n")
    return
}
defer db.Close()

Upvotes: 1

Views: 362

Answers (1)

william.taylor.09
william.taylor.09

Reputation: 2215

Instead of using the hardcoded string, use fmt.Sprintf:

pwd := "password"
db, err := sql.Open("mysql", fmt.Sprintf("root:%s@/events", pwd))

Docs: https://golang.org/pkg/fmt/#Sprintf

Simple GoPlay: https://play.golang.org/p/TKSvTuD8BY

Upvotes: 3

Related Questions