When do I need to explicitly open the SqlConnection?

I wrote the following code (shortened for brevity):

using (SqlConnection cn = new SqlConnection("Server=test;Database=test;User=test;Password=test"))
using (SqlDataAdapter da = new SqlDataAdapter())
using (DataSet ds = new DataSet())
{
    string groupsQuery = @"SELECT GroupName FROM tblGroups ORDER BY GroupName";

    da.SelectCommand = new SqlCommand(groupsQuery, cn);
    da.Fill(ds);

    foreach (System.Data.DataRow row in ds.Tables[0].Rows)
    {
        string group = row["GroupName"].ToString();
        this.GroupList.Add(group);
    }
}

      

I forgot to call it cn.Open()

, but much to my surprise, the code ran fine. I suspected the SqlDataAdapter was doing magic, so I found the source .

The SqlDataAdapter inherits the Fill method from the DbDataAdapter .

Fill calls FillInternal , which wraps its logic in a block like this:

try {
    QuietOpen(activeConnection, out originalState);

    //... do the fill ...
}
finally {
    QuietClose(activeConnection, originalState);
}

      

QuietOpen

and are QuietClose

pretty simple:

static private void QuietClose(IDbConnection connection, ConnectionState originalState) {
    // close the connection if:
    // * it was closed on first use and adapter has opened it, AND
    // * provider implementation did not ask to keep this connection open
    if ((null != connection) && (ConnectionState.Closed == originalState)) {
        // we don't have to check the current connection state because
        // it is supposed to be safe to call Close multiple times
        connection.Close();
    }
}

// QuietOpen needs to appear in the try {} finally { QuietClose } block
// otherwise a possibility exists that an exception may be thrown, i.e. ThreadAbortException
// where we would Open the connection and not close it
static private void QuietOpen(IDbConnection connection, out ConnectionState originalState) {
    Debug.Assert(null != connection, "QuietOpen: null connection");
    originalState = connection.State;
    if (ConnectionState.Closed == originalState) {
        connection.Open();
    }
}

      

I am curious when else I am calling Open

on the SqlConnection, what do I not need? Should I always do this explicitly, or should I let .NET do its job "quietly"?

Also, any link for more details on why the SqlDataAdapter does this would be great.

+3


source to share


1 answer


From this page on MSDN :



The Fill method implicitly opens a Connection , which the DataAdapter uses if it detects that the connection is not yet open. If Fill has opened a connection, it also closes the connection when Fill has finished.

+2


source







All Articles