有人问到这个,就参照DNN的实现,用C#写了一个。记录下来作为备忘。
1 public static DataTable ConvertDataReaderToDataTable(IDataReader reader)
2 {
3 DataTable objDataTable = new DataTable();
4 int intFieldCount = reader.FieldCount;
5 for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
6 {
7 objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter));
8 }
9
10 objDataTable.BeginLoadData();
11
12 object[] objValues = new object[intFieldCount];
13 while (reader.Read())
14 {
15 reader.GetValues(objValues);
16 objDataTable.LoadDataRow(objValues, true);
17 }
18 reader.Close();
19 objDataTable.EndLoadData() ;
20
21 return objDataTable;
22 }
23
2 {
3 DataTable objDataTable = new DataTable();
4 int intFieldCount = reader.FieldCount;
5 for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
6 {
7 objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter));
8 }
9
10 objDataTable.BeginLoadData();
11
12 object[] objValues = new object[intFieldCount];
13 while (reader.Read())
14 {
15 reader.GetValues(objValues);
16 objDataTable.LoadDataRow(objValues, true);
17 }
18 reader.Close();
19 objDataTable.EndLoadData() ;
20
21 return objDataTable;
22 }
23
如果需要的话,columns的详细列属性还可以设置,比如IsDbNull等等。reader还有一个GetSchemaTable的方法,可以获得详细的列属性。