显式关闭 DataSet 的底层连接?
我正在使用 DataSet 从 Microsoft SQL Server 检索数据。我是否需要显式关闭连接(或者底层的SqlDataAdapter自动关闭连接)?
我总是使用 DataReader(using),但第一次使用 DataSet —— 这就是为什么想知道最佳实践。提前致谢。
I am using DataSet to retrieve data from the Microsoft SQL Server. Do I need to explicitly close the connection (or the underlying SqlDataAdapter automatically closes the connection)?
I always use DataReader (with using), but first time using DataSet -- that's why wondering about best practice. Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
DataSet
是数据库上断开连接的“视图”。也就是说,您将数据库中的数据加载到
DataSet
中(实际上是在DataTable
中,可以将其放入DataSet
中),您可以关闭用于填充DataTable
或DataSet
的连接。您可以继续使用数据集中的数据。它不需要与数据库的开放连接。
事实上,一旦您不需要任何数据库访问,就应该立即关闭数据库连接。与数据库的连接应该是短暂的。
A
DataSet
is a disconnected 'view' on the database.That is, you load the data from the database in a
DataSet
(actually, in aDataTable
, which can be put in aDataSet
), and you can close the Connection that you've used to populate theDataTable
orDataSet
.You can continue to work with the data that is in the dataset. It does not require an open connection to the DB.
In fact, you should close a DB-connection as soon as you don't need any DB access soon. Connections to databases should be short-lived.
最佳实践是为所有实现 IDisposable 的 ADO.NET 成员调用 Dispose():连接、命令、适配器、表、集、读取器等:
The best practice is to call
Dispose()
for all ADO.NET members implementedIDisposable
: connection, command, adapter, table, set, reader, etc:using 语句在对象被垃圾收集之前清理非托管资源。连接是非托管资源,因此即使您使用数据集,它也应该关闭。
Using statement clean up unmanaged resources before the object is garbage collected. The connection, is an unmanaged resources so it should be close even if your are with a DataSet.
我始终认为跟踪我的连接是一个好主意,无论我以哪种方式连接到数据库。
你说你总是使用数据读取器,但现在你使用的是数据集。我假设这意味着您正在使用
DataAdapter
来配合您的DataSet
。如果是这种情况,并且您使用的是 MSSQL,那么 SqlDataAdapter 将为您打开和关闭连接,但就像我说的,我喜欢自己跟踪这一点,特别是因为您可能会使用SqlCommand.ExecuteScalar
(即使您大多数时间使用DataAdapter
),并且SqlCommand
不会管理您的连接状态为你。SqlDataAdapter
文档:http://msdn.microsoft.com/en-us/library/zxkb3c3d。 ASPX
I always think it is a good idea to keep track of my connections, no matter wich way I'm connecting to a database.
You said that you always use a datareader, but now you are using a data set. I'm assuming that means you are using a
DataAdapter
to go with yourDataSet
. If that is the case, and you are using MSSQL, then theSqlDataAdapter
will open and close the connection for you, but like I said, I like to keep track of this myself, especially since you may useSqlCommand.ExecuteScalar
(even if you are using aDataAdapter
most of the time) at some point, and theSqlCommand
will not manage your connection state for you.SqlDataAdapter
doc:http://msdn.microsoft.com/en-us/library/zxkb3c3d.aspx
只是为了让事情变得清楚,我遵循传统的初学者与数据库交互的方式。
Just for making things clear i am following conventional beginners way of interacting with db.