首页 > 编程 > .NET > 正文

asp.net中用DataReader高效率分页

2024-07-10 13:24:51
字体:
来源:转载
供稿:网友
分享一下两种方式的分页代码
1.用DataReader分页

复制代码 代码如下:


/// <summary>
/// PageList for DataReader
/// </summary>
/// <param></param>
/// <param></param>
/// <param></param>
/// <param></param>
/// <param></param>
/// <param></param>
/// <param></param>
/// <returns></returns>
public DataTable PageListReader(string connectionString, string sql, int pageSize, int curPage, out int pageCount, out int count, params DbParameter[] cmdParms)
{
int first = 0;
int last = 0;
int fieldCount = 0;
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand cmd = conn.CreateCommand();
PrepareCommand(cmd, conn, null, CommandType.Text, sql, cmdParms);
SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
fieldCount = reader.FieldCount;
for (int i = 0; i < fieldCount; i++)
{
DataColumn col = new DataColumn();
col.ColumnName = reader.GetName(i);
col.DataType = reader.GetFieldType(i);
dt.Columns.Add(col);
}
count = 0;
first = (curPage - 1) * pageSize+1;
last = curPage * pageSize;
while (reader.Read())
{
count++;
if (count >= first && last >= count)
{
DataRow r = dt.NewRow();
for (int i = 0; i < fieldCount; i++)
{
r[i] = reader[i];
}
dt.Rows.Add(r);
}
}
reader.Close();
pageCount = Convert.ToInt32(Math.Ceiling((double)count / (double)pageSize));
return dt;
}
}


2.用ROW_NUMBER()分页

复制代码 代码如下:


/// <summary>
/// 分页获取数据(Sql Server 2005) for ROW_NUMBER()
/// </summary>
/// <param>数据库链接</param>
/// <param>获取数据集的Sql</param>
/// <param>排序字段,可以多个</param>
/// <param>每页显示多少条</param>
/// <param>当前页码</param>
/// <param>总页数</param>
/// <param>总记录数</param>
///<param>DbParameter</param>
/// <returns>DataTable</returns>
public DataTable PageList(string connectionString, string sql, string fldSort, int pageSize, int curPage, out int pageCount, out int count, params DbParameter[] cmdParms)
{
StringBuilder strSql = new StringBuilder();
strSql.AppendFormat(@"SELECT count(0) from {0} as MyTableCount;
select * from (
SELECT ROW_NUMBER() OVER(order by {1}) RowNumber,*
from {0} mytable
) mytable2
where RowNumber between {2} and {3}"
, sql, fldSort, Convert.ToString((curPage - 1) * pageSize + 1), Convert.ToString((curPage * pageSize)));
DataSet ds = ExecuteQuery(connectionString, CommandType.Text, strSql.ToString(), cmdParms);
count = Convert.ToInt32(ds.Tables[0].Rows[0][0]);
pageCount = Convert.ToInt32(Math.Ceiling((double)count / (double)pageSize));
return ds.Tables[1];
}

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表