分享

数据集处理技术 DataReader DataTable DataSet 之间的转换

 青格儿 2009-03-19
      
http://www.cnblogs.com/binarytree/archive/2008/10/09/1306843.html

       绑定Gridview里往往数据源是DataSet 或是DataTable 嗯 ,一些类库(SQLHelper等)里面的方法返回的是DataReader嗯 ,怎么把它们转成DataSet呢?

(1)

DataReader转为DataSet的类:

 

private   DataSet   DataReaderToDataSet(IDataReader   reader)    

  {    

  DataTable   table   =   new   DataTable();    

  int   fieldCount   =   reader.FieldCount;     

  for   (int   i   =   0;   i   <   fieldCount;   i++)    

  {    

  table.Columns.Add(reader.GetName(i),   reader.GetFieldType(i));    

  }    

  table.BeginLoadData();    

  object[]   values   =   new   object[fieldCount];    

  while   (reader.Read())    

  {    

  reader.GetValues(values);    

  table.LoadDataRow(values,   true);    

  }    

  table.EndLoadData();    

  DataSet   ds   =   new   DataSet();    

  ds.Tables.Add(table);    

  return   ds;    

  }

 

(2)

:DataAdapterDataReader是不同的哦

DataAdapter可以这样做:

DataAdapter.Fill(ds)
 
(3)
#region DataReader转换为DataTable
  
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        public static DataTable ConvertDataReaderToDataTable(SqlDataReader reader)
        {
            try
            {
                DataTable objDataTable = new DataTable();
                int intFieldCount = reader.FieldCount;
                for (int intCounter = 0; intCounter < intFieldCount; ++intCounter)
                {
                    objDataTable.Columns.Add(reader.GetName(intCounter), reader.GetFieldType(intCounter));
                }

                objDataTable.BeginLoadData();

                object[] objValues = new object[intFieldCount];
                while (reader.Read())
                {
                    reader.GetValues(objValues);
                    objDataTable.LoadDataRow(objValues, true);
                }
                reader.Close();
                objDataTable.EndLoadData();

                return objDataTable;

            }
            catch (Exception ex)
            {
                throw new Exception("转换出错!", ex);
            }
        }
        #endregion
 
DataTable缓存数据操作:
 
 
如何将SqlDataReader绑定到DataGrid
 
 
C#中提供的精准测试程序运行时间的类Stopwatch
 
 
c#中连接数据库SqlDataAdapter的用法
 
 
SqlDataAdapter它的用法有很多,比DataReader强大多了,感兴趣的朋友可以查查。DataReader是只读的,也就是单向的。而适配器呢,它既可以读又可以写。
 
 
读取Excel内容,导入数据库多张表!
 
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多