C# - 传递 DataTable 与 SqlDataReader
我创建了一个可以使用存储过程名称和 SqlParameters 列表进行调用的方法,我们将其称为 GetData()。然后,GetData() 管理与 SQL Server 的通信并获取数据。然后我需要做的是将数据交还给调用者以供他们读取,他们不需要操作它。我想弄清楚是否最好将 DataTable 或 SqlDataReader 交给调用者?
现在,我认为使用 DataTable 是最好的途径。我对此的决策点是:
- 我返回的数据集很小,不到 100 行和 20 列,因此内存不应该成为问题。
- 据我了解,DataTable 获取所有数据并将其插入 DataTable,然后断开自身连接,以便 GetData() 管理它自己的连接。
- 使用 SqlDataReader,在处理完数据后,我必须管理调用函数中的连接。在 GetData() 中进行调用后,我将无法关闭它,因为我一次只从数据库中读取一行。
这看起来是满足我需要的最佳途径吗?
I have created a method that can be called using a stored procedure name and list of SqlParameters, lets call it GetData(). GetData() then manages talking to the SQL Server and getting the data. What I then need to do is hand the data back to the caller for them to read, they have no need to manipulate it. What I am trying to figure out is if it is best to hand the caller back a DataTable or SqlDataReader?
Right now, I am thinking that going with a DataTable is the best route. My decision points on this are:
- The sets of data I am getting back are small, under 100 rows and 20 columns, so memory shouldn't be an issue.
- From what I understand, a DataTable grabs all of the data and plugs it into the DataTable, then disconnects itself so GetData() would manage it's own connection.
- With a SqlDataReader, I would have to manage the connection in the calling function after I am done with the data. I would not be able to close it after I have made the call in GetData() since I am only reading one row at a time from the database.
Does this seem like the best route to go for what I need?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,你的想法很好。
传回数据表,而不是 sqldatareader。连接仅应维持与数据库服务器之间传输数据所需的最短时间。
Yes, your idea is good.
Pass a datatable back, not the sqldatareader. Connections should only be maintained for the minimum amount of time necessary to transfer data to/from the database server.
使用数据表。数据绑定控件是为了使用该抽象而构建的。
Use a DataTable. The data bound controls are built to use that abstraction.