何时必须显式打开SqlConnection
本文关键字:SqlConnection 何时必 | 更新日期: 2023-09-27 18:28:52
我写了以下代码(为了简洁起见,进行了修剪):
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在变魔术,所以我去找到了源代码。
SqlDataAdapter从DbDataAdapter继承了Fill方法。
Fill调用FillInternal,它将其逻辑封装在一个块中,如下所示:
try {
QuietOpen(activeConnection, out originalState);
//... do the fill ...
}
finally {
QuietClose(activeConnection, originalState);
}
QuietOpen
和QuietClose
非常简单:
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为什么这样做的详细信息的参考都将非常好。
来自MSDN上的此页面:
Fill方法隐式打开DataAdapter如果发现连接尚未打开,则使用。如果填充打开连接,当Fill为完成。