使用SqlDataReader遍历结果集

// 使用SqlDataReader遍历结果集

// DataLooper.cs
/* 数据读取器是实现了System.Data.IDataReader接口的对象,它是快速的、未缓存的、
 * 仅向前的、只读的、已连接数据源的、逐行检索数据的数据流。
 * 它在遍历结果集时,一次只能读取一行。
 * 数据读取器不能直接实例化,而要通过执行命令对象的ExecuteReader方法创建它的实例。
 */
using  System;
using  System.Data;
using  System.Data.SqlClient;
namespace  Ch12
{
     class   DataLooper
    {
         static   void  Main(   string [] args)
        {
             string  strConn =  "server=.\\MSSQL2012;integrated security=true;database=Northwind;" ;
             string  sql =  "select top 5 CustomerID from customers"   ;
            SqlConnection conn =  new  SqlConnection(strConn);
             try
            {
                conn.Open();
                SqlCommand cmd =  new  SqlCommand(sql, conn);
                 //创建数据读取器
                SqlDataReader reader = cmd.ExecuteReader();
                 while  (reader.Read())
                {
                     Console .WriteLine(reader[0]);
                }
                reader.Close();
            }
             catch (   Exception  ex)
            {
                 Console .WriteLine(   "发生错误:"   + ex);
            }
             finally
            {
                conn.Close();
                 Console .ReadLine();
            }
        }
    }
}
-------
ALFKI
ANATR
ANTON
AROUT
BERGS





转载于:https://www.cnblogs.com/bloodfist/p/3273582.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值