diff --git a/sqlx.go b/sqlx.go index 4859d5ac..e95f23ff 100644 --- a/sqlx.go +++ b/sqlx.go @@ -627,10 +627,14 @@ func (r *Rows) StructScan(dest interface{}) error { func Connect(driverName, dataSourceName string) (*DB, error) { db, err := Open(driverName, dataSourceName) if err != nil { - return db, err + return nil, err } err = db.Ping() - return db, err + if err != nil { + db.Close() + return nil, err + } + return db, nil } // MustConnect connects to a database and panics on error. diff --git a/sqlx_test.go b/sqlx_test.go index 5752773a..9502c13e 100644 --- a/sqlx_test.go +++ b/sqlx_test.go @@ -1296,10 +1296,13 @@ type Product struct { // tests that sqlx will not panic when the wrong driver is passed because // of an automatic nil dereference in sqlx.Open(), which was fixed. func TestDoNotPanicOnConnect(t *testing.T) { - _, err := Connect("bogus", "hehe") + db, err := Connect("bogus", "hehe") if err == nil { t.Errorf("Should return error when using bogus driverName") } + if db != nil { + t.Errorf("Should not return the db on a connect failure") + } } func TestRebind(t *testing.T) {