我什么时候必须显式打开SqlConnection?

时间:2014-11-03 16:57:09

标签: c# sqlconnection

我写了下面的代码(为了简洁起见):

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);
    }
}

我忘了拨打cn.Open(),但令我惊讶的是,代码运行得很好。我怀疑SqlDataAdapter做了一些魔术,所以我去了the source

SqlDataAdapter从Fill继承DbDataAdapter方法。

填充调用FillInternal,它将逻辑包装在一个块中,如下所示:

try {
    QuietOpen(activeConnection, out originalState);

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

QuietOpenQuietClose非常简单:

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's 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();
    }
}

我很好奇,还有什么时候我在一个我不需要的SqlConnection上调用Open?我是否应该总是明确地这样做,或者让.NET"静静地"做它的事情?

此外,任何有关SqlDataAdapter执行此操作的详细信息的引用都会很棒。

1 个答案:

答案 0 :(得分:2)

来自this page on MSDN

  

Fill方法隐式打开 DataAdapter 连接   如果发现连接尚未打开,则使用。如果填充   打开连接时,它还会在填充时关闭连接   结束。