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.
If the connection is closed, using SqlDataAdapter.Fill will open the connection http://msdn.microsoft.com/en-us/library/377a8x4t.aspx
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With