阅读量:143
在使用ExecuteReader方法查询数据库时,可以通过设置CommandBehavior.SequentialAccess选项来实现分页读取。具体步骤如下:
- 创建查询语句,例如:
string query = "SELECT * FROM tableName";
- 创建
SqlCommand对象,并设置CommandBehavior为SequentialAccess:
SqlCommand command = new SqlCommand(query, connection);
command.CommandBehavior = CommandBehavior.SequentialAccess;
- 执行查询并获取
SqlDataReader对象:
SqlDataReader reader = command.ExecuteReader();
- 使用
Read方法逐行读取数据:
while(reader.Read())
{
// 读取数据
}
- 在循环中处理分页逻辑,例如:
int pageSize = 10;
int currentPage = 1;
int currentIndex = 0;
while(reader.Read())
{
currentIndex++;
if(currentIndex > (currentPage - 1) * pageSize && currentIndex <= currentPage * pageSize)
{
// 处理当前页数据
}
}
通过以上步骤,可以实现在使用ExecuteReader方法查询数据库时进行分页读取。