Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

go

sqlx

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

like image 841
Piko Monde Avatar asked Oct 17 '25 10:10

Piko Monde


1 Answers

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.

like image 142
jklaw90 Avatar answered Oct 20 '25 03:10

jklaw90



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!