Search code examples
gosqlx

What is the difference between sqlx.Connect() and sqlx.Open()?


I am using jmoiron sqlx library for my golang project. I tried to create a db connection mysql. So, I found these two functions: sqlx.Connect() and sqlx.Open(), but didn't found the difference.

So, I tried to read the documentation in godoc. I found this:

sqlx.Connect()

Connect to a database and verify with a ping.

sqlx.Open()

Open is the same as sql.Open, but returns an *sqlx.DB instead.

I know that sqlx.Open() create a connection to the database using golang sql.Open. But what is sqlx.Connect() use?

If I see inside the source code here:

func Connect(driverName, dataSourceName string) (*DB, error) {
    db, err := Open(driverName, dataSourceName)
    if err != nil {
        return nil, err
    }
    err = db.Ping()
    if err != nil {
        db.Close()
        return nil, err
    }
    return db, nil
}

I can see that it called the same sqlx.Open() then calling db.Ping(). So the the only difference is that sqlx.Open() execute ping after create connection? If so, why it does ping? What makes it different?

Thank you


Solution

  • Connect will use open and ping to check for the valid connection which you can then handle the error.

    Basically you can see right away that the db connection isn't there in one method rather than writing that code yourself again.