如何在会话中保存SQL查询以便以后使用

时间:2014-08-14 18:52:27

标签: c# asp.net session viewstate

我有一个函数,每次按下按钮或每次更改7 DropDownList选项中的任何一个时都会运行查询。如何更改现有方法以使用Session或ViewState,以便我的页面将运行一次查询,然后针对Session或ViewState进行查询,而不是针对每个请求转到我的SQL服务器?

代码隐藏:

protected void Page_Load(object sender, EventArgs e)
{
    strMainQuery = @"SELECT  'http://dddfgdgdfg?objectid=' + CT.OBJECTID + '&classid=1224' 'Task Detail'
            ,LTRIM(RTRIM(CT.ATTR2846)) 'Service'
            ,LTRIM(RTRIM(CT.ATTR2812)) 'Status'
            ,CONVERT(VARCHAR(14), CT.ATTR2752, 110) 'Due Date'
            ,LTRIM(RTRIM(CT.ATTR2739)) 'Task Name'
            ,LTRIM(RTRIM(UA.REALNAME)) 'Owner'
            ,LTRIM(RTRIM(CT.ATTR2799)) 'Client'

        FROM HSI.RMOBJECTINSTANCE1224 CT INNER JOIN HSI.RMOBJECTINSTANCE1232 S ON CT.ATTR2846 = S.ATTR2821 INNER JOIN HSI.USERACCOUNT UA ON S.FK2852 = (UA.USERNUM * -1)";


    if (!Page.IsPostBack)
    {
        ViewState["sortOrder"] = "Asc";
        ViewState["sortExp"] = "Due Date";
        PullData("Due Date", "Asc"); //ASC: A (top) to Z (bottom) || # (low to high) || Date (oldest to newest)
    }
    else
    {
        PullData(ViewState["sortExp"].ToString(), ViewState["sortOrder"].ToString());
    }
}

public void PullData(string sortExp, string sortDir)
{
    string query = "";
    DataTable taskData = new DataTable();
    connString = ""; //connection string
    if (ddlTaskName.SelectedIndex > 0)
    {
        strClause += " AND CT.ATTR2739 = '" + ddlTaskName.SelectedItem.Text + "'";
    }
    else
    {
        strClause += " AND CT.ATTR2739 LIKE '%'";
    }
    if (ddlService.SelectedIndex > 0)
    {
        strClause += " AND CT.ATTR2846 = '" + ddlService.SelectedItem.Text + "'";
    }
    else
    {
        strClause += " AND CT.ATTR2846 LIKE '%'";
    }
    if (ddlStatus.SelectedIndex > 0)
    {
        strClause += " AND CT.ATTR2812 = '" + ddlStatus.SelectedItem.Text + "'";
    }
    else
    {
        strClause += " AND CT.ATTR2812 LIKE '%'";
    }
    if (ddlDueDate.SelectedIndex > 0)
    {
        strClause += " AND CONVERT(VARCHAR(14), CT.ATTR2752, 110) = '" + ddlDueDate.SelectedItem.Text + "'";
    }
    else
    {
        strClause += " AND CONVERT(VARCHAR(14), CT.ATTR2752, 110) LIKE '%'";
    }
    if (ddlOwner.SelectedIndex > 0)
    {
        strClause += " AND UA.REALNAME = '" + ddlOwner.SelectedItem.Text + "'";
    }
    else
    {
        strClause += " AND UA.REALNAME LIKE '%'";
    }
    if (ddlClient.SelectedIndex > 0)
    {
        strClause += " AND CT.ATTR2799 = '" + ddlClient.SelectedItem.Text + "'";
    }
    else
    {
        strClause += " AND CT.ATTR2799 LIKE '%'";
    }

    if (ddlTaskName.SelectedIndex == 0 && ddlService.SelectedIndex == 0 && ddlStatus.SelectedIndex == 0 && ddlDueDate.SelectedIndex == 0 && ddlOwner.SelectedIndex == 0 && ddlClient.SelectedIndex == 0)
    {
        query = strMainQuery + " WHERE CT.ACTIVESTATUS = 0";
    }
    else
    {
        query = strMainQuery + " WHERE CT.ACTIVESTATUS = 0" + strClause;
    }

    using (SqlConnection conn = new SqlConnection(connString))
    {
        try
        {
            SqlCommand cmd = new SqlCommand(query, conn);

            // create data adapter
            SqlDataAdapter da = new SqlDataAdapter(query, conn);
            // this will query your database and return the result to your datatable

            DataSet myDataSet = new DataSet();
            da.Fill(myDataSet);

            DataView myDataView = new DataView();
            myDataView = myDataSet.Tables[0].DefaultView;

            if (sortExp != string.Empty)
            {
                //MessageBox.Show(sortExp);
                //MessageBox.Show(sortDir);
                myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
            }

            yourTasksGV.DataSource = myDataView;
            yourTasksGV.DataBind();

            TasksUpdatePanel.Update();

            conn.Close();
        }
        catch (Exception ex)
        {
            string error = ex.Message;
        }
    }
}

正如您所看到的,每次调用PullData时,它都会运行到SQL服务器并运行查询,一旦我开始拥有越来越多的数据,查询最终会变慢。

如何将现有方法转换为查询一次并保存到Session / ViewState,这样我每次都不必查询SQL服务器?

2 个答案:

答案 0 :(得分:4)

在运行查询之前,请检查缓存。如果它在那里,使用它。如果没有,请运行查询并将结果数据添加到缓存中。

您可以使用Cache.Insert Method (String, Object, CacheDependency, DateTime, TimeSpan)。您可以找到一些很棒的缓存提示:ASP.NET Caching: Techniques and Best Practices

以下是我将如何构造PullData方法:

public void PullData(string sortExp, string sortDir)
{
    // build your query string
    // ...

    // Now create a hash of that query string
    string cacheKey = HashHelper(query);

    DataSet ds = null;

    // check cache if key exists
    if(Cache[cacheKey] != null)
    {
         // read dataset from cache
         ds = (DataSet)Cache[cacheKey];
    }
    else
    {
        // perform sql command and fill your dataset
        // ....
        // save dataset to cache for 30 minutes or whatever you like
        Cache.Insert(cacheKey, ds, null, DateTime.Now.AddMinutes(30), TimeSpan.Zero);
    }

    // Get DataView based on sort options
    DataView myDataView = new DataView();
    myDataView = ds.Tables[0].DefaultView;

    if (sortExp != string.Empty)
    {
        myDataView.Sort = string.Format("{0} {1}", sortExp, sortDir);
    }

    yourTasksGV.DataSource = myDataView;
    yourTasksGV.DataBind();

    TasksUpdatePanel.Update();

    // keep calm and carry on
}

这是我的Hash Helper

private string HashHelper(string query)
{
    using (SHA256Managed hashEngine = new SHA256Managed())
    {
        byte[] data = hashEngine.ComputeHash(Encoding.UTF8.GetBytes(query));
        StringBuilder hash = new StringBuilder(64);
        for (int i = 0; i < data.Length; i++)
        {
            hash.Append(data[i].ToString("x2"));
        }
        return hash.ToString();
    }

}

答案 1 :(得分:1)

使用您当前的代码结构,您无法做到。因为strMainQuery具有不带WHERE子句的sql语句,并且下拉值更改,所以您正在动态构建WHERE子句的条件。因此,您无法将结果集存储在会话中,因为值随每个下拉选择而变化。

这是你可以做的。

  1. 检索strMainQuery没有任何WHERE条件的所有记录,并将结果存储在会话或其他一些状态管理中。因此,您的PullData方法将包含

    SqlCommand cmd = new SqlCommand(strMainQuery, conn);
    
  2. 当下拉值更改时,访问会话对象并使用LINQ根据不同下拉列表的值过滤数据。这至少可以帮助您不为每个下拉列值更改访问数据库服务器,而不是

    获取一次=&gt; store it =&gt;并使用LINQ进行额外的数据过滤

    在绑定以下行中的网格之前,请执行数据过滤。   

    // do the data filtering against the data source based on dropdown selected values
    yourTasksGV.DataSource = myDataView;
    yourTasksGV.DataBind();
    
  3. 我确实看到您在PullData以及!Page.IsPostBack部分else中调用了PageLoad,这意味着此功能PullData将会每次由页面上的任何其他控件触发回发时调用。而是为下拉列表添加OnSelectedIndexChanged事件,并调用PullData方法。