SqlDataAdapter在Fill()函数后关闭SqlConnection吗?

Wac*_*urn 8 .net c# sql-server sqlconnection sqlconnection.close

是否SqlDataAdapter关闭SqlConnectionFill()功能还是需要关闭它自己?

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);
Run Code Online (Sandbox Code Playgroud)

Ada*_*rth 15

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

如果在调用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.
Run Code Online (Sandbox Code Playgroud)

这通常更具可读性,并不依赖于人们理解内部工作原理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);       
    }
Run Code Online (Sandbox Code Playgroud)


Pra*_*ana 5

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

最好的办法是

using(SqlConnection con = new SqlConnection())
{
   // you code 
}
Run Code Online (Sandbox Code Playgroud)

这将自动关闭您的连接

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

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