第四课 使用SqlDataReader读取数据(翻译)

本文档由李欣蔚(nirvana_li)翻译自http://www.csharp-station.com/,转载请注名出处!
更新日期2006-2-14

Lesson 04: Reading Data with the SqlDataReader

使用SqlDataReader读取数据

本课解释了如何使用SqlDataReader对象读取数据。以下是本课的目标:

  • 学习SqlDataReader的用法
  • 了解如何使用SqlDataReader读取数据
  • 了解如何关闭SqlDataReader的必要性

介绍

SqlDataReader是对于大多数有效的情况下读取数据的好的方式。你不能使用它来写入数据。SqlDataReaders通常作为快速的只向前读的数据流。

你能够以只向前的顺序方式从SqlDataReader对象中进行读取。只要你已经读取了某些数据,你必须保存它们,因为你将不能够返回并再一次读取它。

SqlDataReader的只向前读的设计使它很迅速。它并没有遍历数据或者将数据重新写回给数据源的负担。因此,如果你一次只需要读一组数据,并且希望最快速的方法,SqlDataReader则是最好的选择。同样,如果一个单独调用所需要读取的数据量大于内存的存放能力,SqlDataReader的数据流形式应该是一个好的选择。

注意:当讨论为什么应该使用SalDataReader的时候,我在上一段中使用的术语“一次”。任何事情,都有异常发生。在一些情况下,更有效的是使用缓存DataSet。因为缓存超出了本指南的范畴,我们将在下一节课“使用DataSet对象”中讨论它。

创建SqlDataReader对象

得到SqlDataReader对象于实例化其它ADO.NET对象稍微有些不同。你必须对一个command对象调用ExecuteReaer方法,比如这样:

    SqlDataReader rdr = cmd.ExecuteReader();

SqlCommand对象cmdExecuteReader方法返回一个SqlDataReader实例。使用new关键字创建一个SqlDataReader并不做任何事情。前面的课程已经学到,SqlCommand对象引用connectionSQL语句对于SqlDataReader读取数据是必需的。

读取数据

前面的课程包含了使用SqlDataReader的代码,但是关于前面课程中的细节的讨论我们推迟了。这节课建立自你所见到的并解释如何使用SqlDataReader

前面已经解释了,SqlDataReader通过顺序数据流返回数据。为了读取这些数据,你必须从一个表中一行一行的取出数据。只要一行被读取,之前的数据就不再有效。为了再次读取那行,你应该创建一个新的SqlDataReader实例并且再次从数据流中读取它。

SqlDataReader中读取返回的数据流的典型方法是通过while循环迭代没一行。下面的代码显示了如何完成:

      

  while  (rdr.Read())

        
{

               
// get the results of each column

               
string contact = (string)rdr["ContactName"];

               
string company = (string)rdr["CompanyName"];

               
string city    = (string)rdr["City"];

 

               
// print out the results

               Console.Write(
"{0,-25}", contact);

               Console.Write(
"{0,-20}", city);

               Console.Write(
"{0,-25}", company);

               Console.WriteLine();

        }

 

注意在上面代码中的while循环对SqlDataReader对象rdr调用的Read方法。Read方法的返回值为bool,并且只要有记录读取就返回真。在数据流中所有的最后一条记录被读取了,Read方法就返回false

在前面的课程中,我们使用SqlDataReader的索引器,比如rdr[0],提取行中的第一列。你能够使用诸如这样的数值索引器提取行中的列,但是它并不具有很好的可读性。上面的例子使用了字符串索引器,这里的字符串是从SQL查询语句中得到的列名(表的列名如果你使用一个星号,*.字符串下标具有更好的可读性,使得代码能够更好的维护。

无论索引器参数是什么类型,一个SqlDataReader索引器将返回object类型。这就是为什么上面要将结果转换为string的原因。只要值被提取,你能够对它们为所欲为,比如使用Console类型的方法将它们打印到输出。

完结

 

一定要记住关闭SqlDataReader,就像关闭SqlConnection一样。将数据存取代码用try语句块包围起来,并把关闭操作放到finally语句块中,就像这样:

      

  try

        
{

               
// data access code

        }


        
finally

        
{

               
// 3. close the reader

               
if (rdr != null)

               
{

                       rdr.Close();

               }


 

               
// close the connection too

        }
      

上面的代码检测SqlDataReader,确保它不为空。在代码知道SqlDataReader的一个完好的实例存在,它就能够关闭它。Listing1完整的显示了前面各节的代码。

Listing 1: Using the SqlDataReader

using  System;

using  System.Data;

using  System.Data.SqlClient;

 

namespace  Lesson04

{

        
class ReaderDemo

        
{

               
static void Main()

               
{

                       ReaderDemo rd 
= new ReaderDemo();

                       rd.SimpleRead();

               }


 

               
public void SimpleRead()

               
{

                       
// declare the SqlDataReader, which is used in

                       
// both the try block and the finally block

                       SqlDataReader rdr 
= null;

 

                       
// create a connection object

                       SqlConnection conn 
= new SqlConnection(

"Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI");

 

                       
// create a command object

                       SqlCommand cmd  
= new SqlCommand(

                               
"select * from Customers", conn);

 

                       
try

                       
{

                               
// open the connection

                               conn.Open();

 

                               
// 1.  get an instance of the SqlDataReader

                               rdr 
= cmd.ExecuteReader();

 

                               
// print a set of column headers

                               Console.WriteLine(

"Contact Name             City                Company Name");

                               Console.WriteLine(

"------------             ------------        ------------");

 

                               
// 2.  print necessary columns of each record

                               
while (rdr.Read())

                               
{

                                      
// get the results of each column

                                      
string contact = (string)rdr["ContactName"];

                                      
string company = (string)rdr["CompanyName"];

                                      
string city    = (string)rdr["City"];

 

                                      
// print out the results

                                      Console.Write(
"{0,-25}", contact);

                                      Console.Write(
"{0,-20}", city);

                                      Console.Write(
"{0,-25}", company);

                                      Console.WriteLine();

                               }


                       }


                       
finally

                       
{

                               
// 3. close the reader

                               
if (rdr != null)

                               
{

                                      rdr.Close();

                               }


 

                               
// close the connection

                               
if (conn != null)

                               
{

                                      conn.Close();

                               }


                       }
      

               }


        }


}

 

总结

SqlDataReader对象允许你以一种快速的只向前的方式读取数据。你从数据流中读取每一行来读取数据。调用SqlDataReaderClose方法保证资源泄漏不会发生。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值