public DataTable GetPagedData(int pageIndex, int pageSize, string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 使用参数化查询防止SQL注入
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = @"
SELECT *
FROM (SELECT ROW_NUMBER() OVER (ORDER BY SomeColumn) AS RowNum, * FROM YourTable) AS Temp
WHERE RowNum > @startRow AND RowNum <= @endRow";
// 替换参数值
command.Parameters.AddWithValue("@startRow", (pageIndex - 1) * pageSize + 1);
command.Parameters.AddWithValue("@endRow", pageIndex * pageSize);
using (SqlDataAdapter adapter = new SqlDataAdapter(command))
{
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
}
}
ADO.NET 分页
最新推荐文章于 2024-08-22 07:55:06 发布