SQL 从 SQLDataReader 填充数据集的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/510153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best method for Populating DataSet from a SQLDataReader
提问by Andrew Harry
I am working on a DAL that is getting a DataReader Asynchronously.
我正在开发一个异步获取 DataReader 的 DAL。
I would like to write a single method for transforming the DataReader into a DataSet. It needs to handle different schema so that this one method will handle all of my fetch needs.
我想编写一个将 DataReader 转换为 DataSet 的方法。它需要处理不同的模式,以便这种方法可以处理我所有的提取需求。
P.S. I am populating the SQLDataReader Asynchronously, please don't give answers that are getting rid of the DataReader.
PS 我正在异步填充 SQLDataReader,请不要给出摆脱 DataReader 的答案。
回答by Peter Riesz
DataTable.load()can be used for a generic approach.
DataTable.load()可用于通用方法。
do {
var table = new DataTable();
table.Load(reader);
dataset.Tables.Add(table);
} while(!reader.IsClosed);
回答by Matt Hamilton
Try DataSet.Load(). It has several overloads taking an IDataReader.
试试DataSet.Load()。它有几个重载采用 IDataReader。
回答by d.popov
If for some reason the Load method fails, here is a manual way to do it:
如果由于某种原因 Load 方法失败,这是一种手动方法:
DataTable dt = new DataTable();
dt = sdr.GetSchemaTable();
//dt.Constraints.Clear();
//dt.PrimaryKey = null;
//dt.BeginLoadData();
if (sdr.HasRows)
{
DataRow row;
while (sdr.Read())
{
row = dt.NewRow();
sdr.GetValues(row.ItemArray);
dt.Rows.Add(row);
}
Another way is to use SqlTableAdapter:
另一种方法是使用 SqlTableAdapter:
var adapter = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adapter.Fill(ds);