Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does sql.Open() return nil as error when it should not?

Tags:

mysql

go

I am trying to connect to a mysql database.

I tried to see if I would get an error if I gave it wrong connection information but it still returns nil as error. Even If I shut down mysql completely it still does not return an error. What is the point of check for errors after this function if it does not return errors?

This is on Windows, I am using XAMPP and I don't have a password for the database. Username is "root".

import (
    "database/sql"
    "log"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    db, err := sql.Open("mysql", "root@tcp(127.0.0.1:3306)/dbname?charset=utf8")
    if err != nil {
        log.Fatal(err)
    }
    defer db.Close()
}
like image 698
Aiden Avatar asked Sep 18 '26 16:09

Aiden


1 Answers

SQL.Open only creates the DB object, but does not open any connections to the database. If you want to test your connections you have to execute a query to force opening a connection. The common way for this is to call Ping() on your DB object.

See http://golang.org/pkg/database/sql/#Open and http://golang.org/pkg/database/sql/#DB.Ping

like image 132
nussjustin Avatar answered Sep 20 '26 05:09

nussjustin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!