使用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