由于客户对速度和性能上的要求越来越变态,而数据量一天天的庞大,因此本人产生了数据的查询和分页完全由客户端回调来实现。想法看上去复杂,实现起来也不难。废话不多说,看程序吧。
一、存储过程
包头:
create or replace package H_QUERYPACK is
-- Author : Evorul
-- Created : 2007-3-29
-- Purpose : 查询机构表
-- Public type declarations
type MYCURSOR is REF CURSOR;
PROCEDURE QUERYLOG (RET_CURSOR OUT MYCURSOR,ERRORCODE OUT INT,p_logID int,p_StartTime Date,p_EndTime Date,p_Operator varchar2 ,p_OrderField varchar2 ,
p_Desc int,p_PageSize Int,p_PageIndex Int,p_RecordCount Out Int);
end H_QUERYPACK;
包体:
create or replace package body H_QUERYPACK Is
-- Author : Evorul
-- Created : 2007-3-29
-- Purpose : 查询
-- 查询公司,分页用
PROCEDURE QUERYLOG (RET_CURSOR OUT MYCURSOR,ERRORCODE OUT INT,p_logID int,p_StartTime Date,p_EndTime Date,p_Operator varchar2 ,p_OrderField varchar2 ,
p_Desc int,p_PageSize Int,p_PageIndex Int,p_RecordCount Out Int)
AS
v_sql varchar2(3000);
v_sqlcount varchar2(3000);
v_orderfield varchar2(100);
v_order VARCHAR2(5); --顺序
v_count int;
v_heiRownum int;
v_lowRownum int;
BEGIN
ERRORCODE:=0;
v_sql:='select * from LOG Where 1=1 ';
if(p_logID <> 0)then
v_sql := v_sql || ' and id = ' || TO_CHAR(p_logID);
end if;
IF p_Operator Is Not Null Then then
v_sql := v_sql || 'And operator LIKE ''%' || RTRIM(LTRIM(p_Operator))||'%''';
end if;
v_sql := v_sql ||' and (TO_CHAR(time,''YYYYMMDD'') between ''' || to_char(p_StartTime, 'YYYYMMDD') ||''' and ''' || to_char(p_EndTime, 'YYYYMMDD') ||''')';
----取记录总数
v_sqlcount := 'select count(*) from (' || v_sql || ')';
execute immediate v_sqlcount into v_count;
p_RecordCount := v_count;
--排序字段
IF p_OrderField IS NOT NULL THEN
v_orderfield:=p_OrderField;
Else
v_orderfield:='ID';
END IF;
--是否降序
IF p_Desc <>0 THEN
v_order:=' ASC';
Else
v_order:=' DESC';
END IF;
v_sql:=v_sql || 'ORDER BY '|| v_orderfield || v_order;
----执行分页查询
v_heiRownum := p_PageIndex * p_PageSize;
v_lowRownum := v_heiRownum - p_PageSize + 1;
v_sql := 'SELECT * FROM (
SELECT A.*, rownum rn FROM ('|| v_sql ||') A WHERE rownum <= '|| to_char(v_heiRownum) || ') B WHERE rn >= ' || to_char(v_lowRownum) ;
OPEN RET_CURSOR FOR v_sql;
EXCEPTION
WHEN NO_DATA_FOUND THEN
ERRORCODE:=9999;
WHEN OTHERS THEN
ERRORCODE:=9999;
END QUERYLOG;
END H_QUERYPACK;
二、程序
DataAccess.cs
using System;
using System.Data;
using System.Data.OracleClient;
using System.Collections;
using System.Collections.Specialized;
/**//// <summary>
///数据层 author: EvoRul date:2007-03-29
/// </summary>
public class DataAccess
...{
/**//// <summary>
/// 返回数据库连接字符串
/// </summary>
public static String DatabaseConnectionString
...{
get
...{
NameValueCollection configSettings = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings");
return configSettings["connectionString"];
}
}
/**//// <summary>
/// 返回每一页显示的纪录数
/// </summary>
public static int RowsPerPage
...{
get
...{
NameValueCollection configSettings = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appSettings");
return Convert.ToInt32(configSettings["rowsPerPage"]);
}
}
/**//// <summary>
/// 获取特定日志集合
/// </summary>
/// <param name="typeID">日志类型</param>
/// <param name="userID">操作人</param>
/// <param name="strOrderField">排序字段</param>
/// <param name="intASC">是否升序 0-降序,1-升</param>
/// <param name="PageIndex">页码</param>
/// <param name="rowCount">页行数</param>
/// <param name="recordSum">符合条件的总记录数</param>
/// <returns></returns>
public static ArrayList QueryLog(string strOperator,DateTime dtStartTime,DateTime dtEndTime, string strOrderField,
int intASC, int PageIndex, int rowCount, out int recordSum)
...{
// 返回集合
ArrayList myArrayList = new ArrayList();
// 创建连接
OracleConnection myConnection = new OracleConnection(DatabaseConnectionString);
try
...{
// 打开连接
myConnection.Open();
}
catch (Exception ex)
...{
throw (ex);
}
try
...{
// 创建存储过程
OracleCommand myCommand = new OracleCommand("H_QUERYPACK.QUERYLOG", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
OracleDataReader dr;
// ============================== 参数定义 ==============================
// 返回值
myCommand.Parameters.Add("RET_CURSOR", OracleType.Cursor);
myCommand.Parameters["RET_CURSOR"].Direction = ParameterDirection.Output;
OracleParameter ret = myCommand.Parameters.Add("ERRORCODE", OracleType.Int32);
ret.Direction = ParameterDirection.Output;
OracleParameter retCountSum = myCommand.Parameters.AddWithValue("p_RecordCount", OracleType.Int32);
retCountSum.Direction = ParameterDirection.Output;
// 编号
myCommand.Parameters.AddWithValue("p_logID", OracleType.Int32).Value = 0;
// 用户编号
myCommand.Parameters.AddWithValue("p_Operator", OracleType.VarChar).Value = strOperator;
// 时间下限
myCommand.Parameters.AddWithValue("p_StartTime", OracleType.DateTime).Value = dtStartTime;
// 时间上限
myCommand.Parameters.AddWithValue("p_EndTime", OracleType.DateTime).Value =dtEndTime;
// 排序字段
myCommand.Parameters.AddWithValue("p_OrderField", OracleType.VarChar).Value = strOrderField;
// 怎么排序
myCommand.Parameters.AddWithValue("p_Desc", OracleType.Int32).Value = intASC;
// 每页行数
myCommand.Parameters.AddWithValue("p_PageSize", OracleType.Int32).Value = rowCount;
//页码
myCommand.Parameters.AddWithValue("p_PageIndex", OracleType.Int32).Value = PageIndex;
// ============================ 参数定义完毕 ============================
// 执行存储过程
dr = myCommand.ExecuteReader();
// 执行未成功
if (Convert.ToInt32(ret.Value) != 0)
throw new Exception("执行存储过程出错!");
// 总记录数
recordSum = Convert.ToInt32(retCountSum.Value);
while (dr.Read())
...{
// 创建新日志
Log log = new Log();
//操作业务类型
if (dr["operationtype"] != DBNull.Value)
...{
log.OperationType = Convert.ToString(dr["operationtype"]);
}
// 时间
if (dr["time"] != DBNull.Value)
log.Time = Convert.ToDateTime(dr["time"]);
// 用户
if (dr["operator"] != DBNull.Value)
...{
log.Operator = Convert.ToString(dr["operator"]);
}
// 信息
if (dr["info"] != DBNull.Value)
log.Info = Convert.ToString(dr["info"]);
// 加入返回集合
myArrayList.Add(log);
}
dr.Close();
return myArrayList;
}
catch (Exception ex)
...{
throw (ex);
}
finally
...{
myConnection.Close();
}
}
}
DataLogic.cs
using System;
using System.Data;
using System.Configuration;
using System.Collections;
/**//// <summary>
/// 业务逻辑层 author: EvoRul date:2007-03-29
/// </summary>
public class DataLogic
...{
public DataLogic()
...{
}
public static int recordSum = 0;
/**//// <summary>
/// 查询日志
/// </summary>
/// <param name="strOperator">操作人</param>
/// <param name="dtStarTime">时间范围下限</param>
/// <param name="dtEndTime">时间上限</param>
/// <param name="Pageid">页码</param>
/// <returns></returns>
public static IEnumerable GetLogData(string strOperator,DateTime dtStarTime,DateTime dtEndTime, string Pageid)
...{
return Log.GetList(strOperator,dtStarTime,dtEndTime,"time",1, Convert.ToInt32(Pageid),DataAccess.RowsPerPage,out recordSum);
}
}
Log.cs
using System;
using System.Data;
using System.Collections;
/**//// <summary>
/// 日志类
/// </summary>
public class Log
...{
// ============================== 成员 ==============================
protected string operationType;
/**//// <summary>
/// 时间
/// </summary>
protected DateTime time = new DateTime();
/**//// <summary>
/// 用户
/// </summary>
protected string m_operator;
/**//// <summary>
/// 信息
/// </summary>
protected string info = "";
// ============================== 属性 ==============================
public string OperationType
...{
get ...{ return operationType; }
set ...{ operationType = value; }
}
/**//// <summary>
/// 时间
/// </summary>
public DateTime Time
...{
get ...{ return time; }
set ...{ time = value; }
}
/**//// <summary>
/// 用户
/// </summary>
public string Operator
...{
get ...{ return m_operator; }
set ...{ m_operator = value; }
}
/**//// <summary>
/// 信息
/// </summary>
public string Info
...{
get ...{ return info; }
set ...{ info = value; }
}
// ============================== 方法 ==============================
/**//// <summary>
/// 创建空日志实例
/// </summary>
public Log()
...{
}
/**//// <summary>
/// 新增日志
/// </summary>
public void Add()
...{
try
...{
// 暂不支持该方法
throw new Exception("新增日志");
}
catch (Exception ex)
...{
throw (ex);
}
}
/**//// <summary>
/// 修改日志(不支持)
/// </summary>
public void Modify()
...{
// 暂不支持该方法
throw new Exception("修改日志");
}
/**//// <summary>
/// 删除日志
/// </summary>
public void Del()
...{
// 暂不支持该方法
throw new Exception("修改日志");
}
/**//// <summary>
/// 获取特定的日志集
/// </summary>
/// <param name="strOperator">操作人</param>
/// <param name="dtStartTime">开始时间</param>
/// <param name="dtEndTime">结束时间</param>
/// <param name="strOrderField">排序字段</param>
/// <param name="intASC">0-降序,1-升序</param>
/// <param name="PageIndex">页码</param>
/// <param name="rowCount">页行数</param>
/// <param name="recordSum">总记录数</param>
/// <returns></returns>
public static ArrayList GetList(string strOperator,DateTime dtStartTime,DateTime dtEndTime,string strOrderField,int intASC, int PageIndex, int rowCount, out int recordSum)
...{
return DataAccess.QueryLog(strOperator,dtStartTime,dtEndTime,strOrderField, intASC, PageIndex, rowCount, out recordSum);
}
}
前台页 Default.aspx
<%...@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>客户端回调</title>
<style type="text/CSS">...
body {...}{
font-size: 12px;
color: #525252;
}
td {...}{
font-size: 12px;
color: #525252;
}
th {...}{
font-size: 12px
}
a:link {...}{
color: #000000; text-decoration: none
}
a:visited {...}{
color: #525252; text-decoration: none
}
a:hover {...}{
color: #0095A7; text-decoration: underline
}
td.alt_1 {...}{
border-top: 1px solid #d6d6d6;
border-right: 1px solid #d6d6d6;
font-size:12px;
color: #4f6b72;
}
td.alt_2 {...}{
border-top: 1px solid #d6d6d6;
border-right: 1px solid #d6d6d6;
}
td.alt_3 {...}{
border-left: 1px solid #d6d6d6;
border-bottom: 1px solid #d6d6d6;
}
td.alt_4 {...}{
border-left: 1px solid #d6d6d6;
border-right: 1px solid #d6d6d6;
}
</style>
<script type="text/javascript">...
//author: EvoRul date:2007-03-25
var PageIndex=1;
function QueryServer(objOperator,objStartTime,objEndTime,intIndex,boolReset)
...{
context = gridspan;
context.innerHTML = "<IMG SRC='http://www.mbsky.com/images/pie.gif' />数据加载中...";
arg = "ServerMethodQuery|" + objOperator.value.replace(/$/g,"")+"$"+ objStartTime.value.replace(/$/g,"")+"$"+ objEndTime.value.replace(/$/g,"") +"$"+ intIndex.toString().replace(/$/g,"")+"$"+ boolReset.toString().replace(/$/g,"");
<%= ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context")%>;
}
function ReceiveServerData(result, context)
...{
context.innerHTML = (result.split('$'))[0];
var t1=document.getElementById("RecordSum");
var t2=document.getElementById("PageSum");
var t3=document.getElementById("CurrentPage");
var t5=document.getElementById("LinkUp");
var t6=document.getElementById("Linkdown");
var t7=document.getElementById("DownListIndex");
t1.innerHTML = (result.split('$'))[1];
t2.innerHTML = (result.split('$'))[2];
t3.innerHTML = (result.split('$'))[3];
PageIndex=eval((result.split('$'))[3]);
if(PageIndex>1)
...{
t5.innerHTML="<a href="#" onclick="QueryServer(txtOperator,TxtStartTime,TxtEndTime,"+(PageIndex-1).toString()+",'false')">上一页</a>";
}
else
t5.innerHTML = "上一页";
if(PageIndex< eval((result.split('$'))[2]))
...{
t6.innerHTML="<a href="#" onclick="QueryServer(txtOperator,TxtStartTime,TxtEndTime,"+(PageIndex+1).toString()+",'false')">下一页</a>";
}
else
t6.innerHTML="下一页";
if(result.split('$').length>4)
...{
var t4=document.getElementById("SpanIndex");
t4.innerHTML = (result.split('$'))[4];
}
t7.value=PageIndex;
}
function functionPageload()
...{
if(document.readyState!="complete") return;
context = gridspan;
arg = "ServerMethodQuery|" +"$"+"1753-1-1"+ "$"+"9999-12-31"+ "$"+ "1"+"$"+ "true";
<%= ClientScript.GetCallbackEventReference(this, "arg", "ReceiveServerData", "context")%>;
//页面加载完后执行的代码
}
//页面加载状态改变时执行的方法
document.onreadystatechange=functionPageload;
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table style="width:100%; background-color:#ffffff; margin: 0px;" cellpadding="0" cellspacing="0" border="0" id="table1">
<tr>
<td style="width:102%; height: 445px;" align="center" valign="top">
<br />
<table cellpadding="0" cellspacing="0" border="0" width="95%">
<tr>
<td><img src="http://www.mbsky.com/images/round-1.gif" width="13" height="30" alt="" /></td>
<td style="width:100%;background-color:#efefef;" class="alt_1">
日志查询</td>
</tr>
<tr>
<td class="alt_4" valign="top" colspan="2" align="center">
<table cellpadding="0" cellspacing="0" border="0" width="95%">
<tr>
<td style="width:120px; height:30px;" align="right">
操作人员:</td>
<td align="left" style="width: 143px">
<asp:TextBox ID="txtOperator" runat="server" CssClass="border" ReadOnly="False"
Width="90px"></asp:TextBox></td>
<td style="width:71px; height:30px;" align="right">
操作时间:</td>
<td align="left">
<asp:TextBox ID="TxtStartTime" runat="server" CssClass="border"
ReadOnly="False" Width="90px"></asp:TextBox>-<asp:TextBox
ID="TxtEndTime" runat="server" CssClass="border"
ReadOnly="False" Width="90px"></asp:TextBox></td>
</tr>
<tr>
<td colspan="4" style="background-image:url(../images/point.gif); height:12px;"></td>
</tr>
<tr>
<td colspan="4" style="height:30px; text-align: center;">
<asp:Button ID="Submit" runat="server" CssClass="btn2" Text=" 确定 " Height="20px" Width="50px" /></td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<table cellpadding="0" cellspacing="0" border="0" width="100%">
<tr>
<td style="width:100%;" class="alt_3"> </td>
<td></td>
</tr>
</table>
</td>
</tr>
</table>
<span id="gridspan">
<asp:GridView ID="Logs" runat="server" AutoGenerateColumns="False"
GridLines="Horizontal" PageSize="15"
Width="95%" BackColor="White" BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4">
<RowStyle ForeColor="#333333" Height="24px" BackColor="White" />
<SelectedRowStyle BorderColor="Red" BackColor="#339966" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#336666" ForeColor="White" Height="30px" Font-Bold="True" />
<AlternatingRowStyle BorderWidth="1px" />
<Columns>
<asp:TemplateField HeaderText="用户">
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="" Text='<%# Eval("UserInfo.Name") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="类型">
<ItemTemplate>
<asp:HyperLink ID="HyperLink2" runat="server" NavigateUrl="" Text='<%# Eval("Type.Name") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="时间">
<ItemTemplate>
<asp:HyperLink ID="HyperLink4" runat="server" NavigateUrl="" Text='<%# Eval("Time") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="备注">
<ItemTemplate>
<asp:HyperLink ID="HyperLink5" runat="server" NavigateUrl="" Text='<%# Eval("Info") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#333333" />
<PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
</asp:GridView>
</span>
<table border="0" cellpadding="0" cellspacing="0" bordercolorlight="#000000" bordercolordark="#ffffff">
<tr>
<td align="center" nowrap style="height: 25px; width: 601px;">
共有<asp:Label ID="RecordSum" runat="server" />条<asp:Label ID="PageSum" runat="server" />页结果
当前显示为第<asp:Label ID="CurrentPage" runat="server" />页 15条/页
<asp:Label ID="LinkUp" runat="server" >上一页</asp:Label>
<asp:Label ID="Linkdown" runat="server" >下一页</asp:Label>
跳转至第<span id="SpanIndex"><asp:DropDownList ID="DownListIndex" runat="server" Width="50px">
</asp:DropDownList></span>页
</td>
</tr>
</table>
<asp:ObjectDataSource ID="DataSourceLog" runat="server" TypeName="DataLogic" SelectMethod="GetLogData">
<SelectParameters>
<asp:ControlParameter ControlID="txtOperator" DefaultValue=" " Name="strOperator" PropertyName="Text"
Type="string" />
<asp:ControlParameter ControlID="TxtStartTime" DefaultValue="1753-1-1" Name="dtStarTime"
PropertyName="Text" Type="DateTime" />
<asp:ControlParameter ControlID="TxtEndTime" DefaultValue="9999-12-31" Name="dtEndTime"
PropertyName="Text" Type="DateTime" />
<asp:ControlParameter Name="Pageid" ControlID="DownListIndex" DefaultValue="1" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.IO;
using System.Text;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;
public partial class _Default : System.Web.UI.Page,ICallbackEventHandler
...{
protected void Page_Load(object sender, EventArgs e)
...{
this.Submit.Attributes.Add("onclick", "QueryServer(txtOperator,TxtStartTime,TxtEndTime,1,"true");return false;");
this.DownListIndex.Attributes.Add("onchange", "QueryServer(txtOperator,TxtStartTime,TxtEndTime,this.value,"false");return false;");
}
回调分页#region 回调分页
private string serverReturn;
public string GetCallbackResult()
...{
string[] parts = serverReturn.Split('|');
//根据传递的方法名进行调用,并传递相应的参数,目前只支持一个参数
return (string)GetType().GetMethod(parts[0]).Invoke(this, new object[] ...{ parts[1] });
}
public void RaiseCallbackEvent(string eventArgument)
...{
serverReturn = eventArgument;
}
/**//// <summary>
/// 根据从客户端传来的值,对GridView的内容进行更新,并将更新后的GridView的html返回
/// </summary>
/// <param name="arg"></param>
/// <returns></returns>
public string ServerMethodQuery(string arg)
...{
Logs.DataSourceID = "DataSourceLog";
string[] arrayArg = arg.Split('$');
this.txtOperator.Text = arrayArg[0];
this.TxtStartTime.Text= arrayArg[1];
this.TxtEndTime.Text = arrayArg[2];
intialPageSelect();
this.DownListIndex.SelectedValue = arrayArg[3];
Logs.DataBind();
//传入客户端字符串,并用"$"分割
StringBuilder strHtml = new StringBuilder();
strHtml.Append(RenderControl(Logs));
strHtml.Append("$");
strHtml.Append(DataLogic.recordSum.ToString());
strHtml.Append("$");
strHtml.Append(Convert.ToString(DataLogic.recordSum / DataAccess.RowsPerPage + 1));
strHtml.Append("$");
strHtml.Append(arrayArg[3]);
if (arrayArg[4] == "true")
...{
strHtml.Append("$");
intialPageSelect();
strHtml.Append(RenderControl(DownListIndex));
}
return strHtml.ToString();
}
private string RenderControl(Control control)
...{
StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
HtmlTextWriter writer2 = new HtmlTextWriter(writer1);
control.RenderControl(writer2);
writer2.Flush();
writer2.Close();
return writer1.ToString();
}
/**//// <summary>
/// 初始化页下拉单
/// </summary>
private void intialPageSelect()
...{
DownListIndex.Items.Clear();
for (int i = 0; i < (DataLogic.recordSum / DataAccess.RowsPerPage + 1); i++)
...{
this.DownListIndex.Items.Add(Convert.ToString(i + 1));
}
}
#endregion
}
如有错误,欢迎指正!