Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if I dont open instance of SqlConnection?

Tags:

c#

sql-server

I am reviewing a piece of code in a application and I came to something very strange in regard to connecting to database.

It is executing queries without opening the connection like this:

using (sqlConnection1 = new SqlConnection(connString)
{
    SqlCommand comm = new SqlCommand(query,sqlConnection1);

    // ... parameters are handled here...

    SqlDataAdapter ad = new SqlDataAdapter(comm);
    ds = new DataSet();
    ad.FillSchema(ds, SchemaType.Source);
    ad.Fill(ds);
}

Shouldnt it fail because of connection is not open? I actually tested this in separate project and it worked.

like image 238
NeverStopLearning Avatar asked Dec 07 '22 05:12

NeverStopLearning


2 Answers

If the connection is closed, using SqlDataAdapter.Fill will open the connection http://msdn.microsoft.com/en-us/library/377a8x4t.aspx

like image 183
tim Avatar answered Dec 09 '22 16:12

tim


Per the documentation, SqlDataAdapter will open the conenction if it isn't already open, and return it to its previous state.

The connection object associated with the SelectCommand must be valid, but it does not need to be open. If the connection is closed before FillSchema is called, it is opened to retrieve data, then closed. If the connection is open before FillSchema is called, it remains open.

Fill also behaves in the same manner

like image 36
Rowland Shaw Avatar answered Dec 09 '22 15:12

Rowland Shaw