在使用ExecuteReader
方法查詢數(shù)據(jù)庫時,可以通過設置CommandBehavior.SequentialAccess
選項來實現(xiàn)分頁讀取。具體步驟如下:
string query = "SELECT * FROM tableName";
SqlCommand
對象,并設置CommandBehavior為SequentialAccess
:SqlCommand command = new SqlCommand(query, connection);
command.CommandBehavior = CommandBehavior.SequentialAccess;
SqlDataReader
對象:SqlDataReader reader = command.ExecuteReader();
Read
方法逐行讀取數(shù)據(jù):while(reader.Read())
{
// 讀取數(shù)據(jù)
}
int pageSize = 10;
int currentPage = 1;
int currentIndex = 0;
while(reader.Read())
{
currentIndex++;
if(currentIndex > (currentPage - 1) * pageSize && currentIndex <= currentPage * pageSize)
{
// 處理當前頁數(shù)據(jù)
}
}
通過以上步驟,可以實現(xiàn)在使用ExecuteReader
方法查詢數(shù)據(jù)庫時進行分頁讀取。