11

SqlDataAdapter关闭函数SqlConnection之后Fill()还是我需要自己关闭它?

string cnStr = @"Data Source=TEST;Initial Catalog=Suite;Persist Security Info=True;User ID=app;Password=Immmmmm";
cn = new SqlConnection(cnStr);
SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Date", cn);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();
adapter.Fill(ds);

cn.Close() // ????????

Console.WriteLine(ds.Tables[0].Rows.Count);
Console.WriteLine(cn.State);
4

2 回答 2

16

在您当前的使用中,它将为您关闭:

如果在调用 Fill 之前关闭了 IDbConnection,则打开它以检索数据,然后关闭它。如果在调用 Fill 之前连接已打开,则它保持打开状态。

http://msdn.microsoft.com/en-us/library/zxkb3c3d.aspx

我认为最好自己明确地用一个using声明来满足它:

using (SqlConnection conn = new SqlConnection(""))
{
    conn.Open();

    // Do Stuff.

} // Closes here on dispose.

这通常更具可读性,并且不依赖于人们理解 的内部工作原理SqlDataAdapter.Fill,只依赖于using语句和连接。

但是,如果您知道连接在适配器使用它之前已关闭(例如,您刚刚创建了连接)并且它没有用于其他任何事情,那么您的代码是完全安全和有效的。

就个人而言,我会写这样的东西:

    string cnStr = "Data Source=TEST;Initial Catalog=Suite;Persist Security Info=True;User ID=app;Password=Immmmmm";
    DataSet ds = new DataSet();

    using (SqlConnection cn = new SqlConnection(cnStr))
    using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM Date", cn))
    using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
    { 
        conn.Open();
        adapter.Fill(ds);       
    }
于 2011-09-12T13:36:03.880 回答
5

据我所知,您需要自己关闭连接

最好的办法是

using(SqlConnection con = new SqlConnection())
{
   // you code 
}

这将自动关闭您的连接

在处理一次性对象时,使用 C# 中的块非常方便。Disposable 对象是那些在调用 dispose 时可以显式释放它们使用的资源的对象。正如我们所知,.Net 垃圾收集是非确定性的,因此您无法准确预测对象何时会被垃圾收集。

阅读这篇文章以获取更多详细信息:了解 C# 中的“使用”块

于 2011-09-12T13:36:19.293 回答