Answer the question
In order to leave comments, you need to log in
Why doesn't sql.Open('mysql', wrongConnString) return an error?
Good afternoon.
I decided to "play around" with go in practice. I don't understand why (1) doesn't return an error?! The error is caught on (3)
db, err := sql.Open("mysql", wrongConnString) // 1
if err != nil {
fmt.Println(err.Error())
} else {
fmt.Println("db is connected")
}
defer db.Close() // 2
if err = db.Ping(); err != nil { // 3
fmt.Println("db is not connected")
fmt.Println(err.Error())
}
if db, err := sql.Open("mysql", rightConnString); err != nil {
//...
}
Answer the question
In order to leave comments, you need to log in
Your connString is probably syntactically correct, which is why the error doesn't occur. The connection to the database itself occurs later.
About the second. Your db variable is created inside the if condition, so it is visible only in the scope of that block. Create it before this ifa.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question