在使用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
方法查詢數據庫時進行分頁讀取。