把Datareader转化为DataTable
我们常在用三层框架返回数据集的时候,有时需要把Datareader转化为DataTable,实现的代码如下:
public DataTable ConvertDataReaderToDataTable(SqlDataReader dataReader)
{
DataTable datatable = new DataTable();
DataTable schemaTable = dataReader.GetSchemaTable();
//动态添加列
try
{
foreach(DataRow myRow in schemaTable.Rows)
{
DataColumn myDataColumn = new DataColumn();
myDataColumn.DataType = myRow.GetType();
myDataColumn.ColumnName = myRow[0].ToString();
datatable.Columns.Add(myDataColumn);
}
//添加数据
while(dataReader.Read())
{
DataRow myDataRow = datatable.NewRow();
for(int i=0;i<schemaTable.Rows.Count;i++)
{
myDataRow[i] = dataReader[i].ToString();
}
datatable.Rows.Add(myDataRow);
myDataRow = null;
}
schemaTable = null;
return datatable;
}
catch(Exception ex)
{
Error.Log(ex.ToString());
return datatable;
}
}