DataReader是一个简单的数据集,用于从数据源中检索只读、只向前数据流。数据流是为缓冲的,所以在检索大量数据时,DataReader是明智的选择。DataReader对象是通过Command对象的ExecuteReader方法从数据源中检索行创建。
DataReader 有read和get两个方法。
C#的例子:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConDataRead0821usingSystem;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConDataRead0821
{
classProgram
{
static void Main(string[] args)
{
SqlConnection cn = new SqlConnection(@"Data Source=DBCN;InitialCatalog=test;Integrated Security=True");
cn.Open();
SqlCommand cm = new SqlCommand("select * from lucy", cn);
SqlDataReader read = cm.ExecuteReader();
while (read.Read())
{
Console.WriteLine(read.GetInt32(0) + "," + read.GetString(1) + ","+ read.GetInt32(2));
}
read.Close();
cn.Close();
Console.ReadLine();
}
}
}
当在Command对象中封装多条SQL语句时,会产生多个数据集,这时就可以使用DataReader对象的NextResult方法来顺序访问这些数据
实例:
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace DataReadernextresult
{
classProgram
{
static void Main(string[] args)
{
SqlConnection cn = new SqlConnection(@"Data Source=DBCN;InitialCatalog=test;Integrated Security=True");
string str1 = "select id,name from lucy whereid<3";
str1 += "select id,name from lucy where book ='a'";
SqlCommand cm = new SqlCommand(str1,cn);
cn.Open();
SqlDataReader read = cm.ExecuteReader();
do
{
Console.WriteLine("t{0}t{1}", read.GetName(0),read.GetName(1));
while (read.Read())
{
Console.WriteLine("t{0}t{1}", read.GetInt32(0),read.GetString(1));
}
} while (read.NextResult());
read.Close();
cn.Close();
Console.ReadLine();
}
}
}