N
N
nurdus2018-02-04 13:24:59
go
nurdus, 2018-02-04 13:24:59

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())
  }

And second, if 1 is rewritten like this, then go does not see the db variable (on line 2):
if db, err := sql.Open("mysql", rightConnString); err != nil {
    //...
  }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Pavlyuk, 2018-02-04
@nurdus

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 question

Ask a Question

731 491 924 answers to any question