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

本文关键字:查询 SQL 会话 保存 | 更新日期: 2023-09-27 18:18:15

我有一个函数,每次按下按钮或每次更改7个下拉列表中的任何一个选择时运行查询。我怎么能改变现有的方法来使用会话或ViewState,所以我的页面将运行查询一次,然后对会话或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服务器并运行查询,一旦我开始有越来越多的数据,查询最终会变慢。

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

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

执行查询前,请检查缓存。如果有,就使用它。如果没有,则运行查询并将结果数据添加到Cache中。

你可以使用缓存。插入方法(String, Object, CacheDependency, DateTime, TimeSpan)。您可以找到一些很棒的缓存技巧:. NET缓存:技术和最佳实践。

下面是我将如何构建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
}

这是我的哈希助手

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();
    }
}

以你目前的代码结构,你做不到。因为您的strMainQuery具有没有WHERE子句的sql语句,并且随着下拉值的变化,您正在动态构建WHERE子句的条件。所以你不能在会话中存储结果集,因为每个下拉选择的值都会改变。

你可以这样做。

  1. 检索strMainQuery的所有记录,不带任何WHERE条件,并将结果存储在会话或其他状态管理中。所以你的PullData方法将包含

    SqlCommand cmd = new SqlCommand(strMainQuery, conn);
    
  2. 随着下拉值的变化,访问会话对象并使用LINQ根据不同下拉值过滤数据。这至少可以帮助您避免每次下拉值更改都访问数据库服务器,而不是

    读取一次=>存储=>并使用LINQ进行额外的数据过滤

    在下面的行中绑定网格之前,进行数据过滤。

    // do the data filtering against the data source based on dropdown selected values
    yourTasksGV.DataSource = myDataView;
    yourTasksGV.DataBind();
    

我确实看到您在!Page.IsPostBack以及else部分的PageLoad中调用PullData,这意味着每次由页面上的任何其他控件触发回发时都会调用此函数PullData。而是为下拉菜单添加一个OnSelectedIndexChanged事件并调用PullData方法。