使用DataReader对象中的Read方法用来遍历整个结果集,不需要显式的向前移动指针,或者检查文件的结果,如果没有要读取的记录了,则Read方法会自动返回False。例如,实现用来读取一个查询所有记录的典型循环,代码如下:
using (SqlConnection conn=new SqlConnection(connString))
{
SqlCommand cmd=new SqlCommand("Select * from customers", conn);//查询customers表
cmd.Connection.Open();//打开数据库连接
SqlDataReader reader=cmd.ExecuteReader();
While(reader.Read())//循环读取数据
//将companyname的值添加到CustomeList中
CustomerList.Items.Add(reader["companyname"].ToStrin());
reader.Close();关闭数据库连接
}
注意:要使用SqlDataReader,必须调用SqlCommand对象的ExecuteReader()方法来创建,而不要直接使用构造函数。