[英]Does SqlDataAdapter close the SqlConnection after Fill() function?
SqlDataAdapter
是在Fill()
函数之后关闭SqlConnection
还是我需要自己关闭它?
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);
在您当前的用法中,它将为您关闭:
如果IDbConnection在调用Fill之前关闭,则将其打开以检索数据,然后关闭。 如果在调用Fill之前连接已打开,则它将保持打开状态。
http://msdn.microsoft.com/zh-CN/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);
}
据我所知,您需要自己关闭连接
最好的方法是
using(SqlConnection con = new SqlConnection())
{
// you code
}
这将自动关闭您的连接
在处理一次性对象时,在C#中使用block非常方便。 一次性对象是那些可以显式释放它们在被调用以处置时所使用的资源的对象。 众所周知,.Net垃圾回收是不确定的,因此您无法预测对象何时将被垃圾回收。
请阅读此帖子以获取更多详细信息: 了解C#中的“ using”块
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.