ASP.NET:适配器填充数据集后是否应该立即关闭连接?
我正在使用 GridView,想知道在语句之后立即关闭连接是否对我更好
adapter.Fill(ds);
,或者我应该等到完成:
GridView.DataSource = ds;
GridView.DataBind();
我假设一旦数据集被填充,我就不再需要连接。我错了吗?
I am using a GridView and wonder if it's better for me to close the connection IMMEDIATELY after the
adapter.Fill(ds);
statement or I should wait until I've done:
GridView.DataSource = ds;
GridView.DataBind();
I assume once the dataset has been filled, I no longer need the connection. Am I wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您调用
adapter.Fill(ds);
时,数据将加载到内存中,您可以在执行此语句后立即关闭连接。之后,当您将 ds 设置为 gridview 的 DataSource 时,它将绑定内存中的数据。请阅读本文以了解使用断开连接的数据 - DataSet 和 SqlDataAdapter
When you call
adapter.Fill(ds);
the data is loaded into memory and you can close the connection immediately after this statement. After, when you set ds as DataSource to the gridview, it will bind the data from memory.Have a look into this article for understanding Working with Disconnected Data - The DataSet and SqlDataAdapter
调用
Fill()
后,您可以安全地关闭连接。题外话:使用使用
块在处理
IDisposable
(如SqlConnection
)实体时,因此,在这种情况下,您不必手动调用关闭()
。After call to
Fill()
, you can safely close the connection. Offtopic: make it a practice usingusing
block when dealing withIDisposable
(likeSqlConnection
) entities so, in this case, you wouldn't have to manually callClose()
.将数据填充到 DataSet 后,SqlDataAdapter 不需要连接,但如果您在此之后进行任何数据操作您需要再次打开它,我所做的是将所有此类语句写入
finally
块。SqlDataAdapter
doesn't needconnection
after filling data intoDataSet
, but if you are doing anydata manipulation
after that line you will need to open it again, what i do is i write all such statements infinally
block.根本不需要打开
SqlConnection
,因为DataSet
具有断开连接的体系结构。一个非常基本的使用示例将是
来源:对比ADO.NET DataReader 和 DataSet
There is no need to open the
SqlConnection
at all asDataSet
has a disconnected architecture.A very basic example of usage will be
Source: Contrasting the ADO.NET DataReader and DataSet