追求新生活 名字2008

活着的意义

cache初接触,并利用了DataView

我们在写代码的时候,如果数据控件要获得数据,一般方法,
            Conn.Open();
            OleDbCommand cmd;
            cmd = new OleDbCommand(sql, Conn);
            GridView1.DataSource = dbcenter.accessGetDataSet(sql);
            GridView1.DataBind();
         Conn.close();
但如果多个数据控件要绑定数据,则比较频繁打开数据库,效率一定大打折扣了。
所以我们要用上cache,并巧妙利用DataView 获取数据
原来代码
string sql = "select * from dbs where inf_type='ok' order by news_no desc";
         string sql2 = "select * from dbs where inf_type='chinese' order by news_no desc";
         string sql3 = "select * from dbs where inf_type='english' order by news_no desc";
          string sql4.....
OleDbConnection Conn = cs.Acce_Conn();
Conn.Open();
            OleDbCommand cmd;
            cmd = new OleDbCommand(sql, Conn);
            GridView1.DataSource = cs.accessGetDataSet(sql);
            GridView1.DataBind();
            GridView2.DataSource = cs.accessGetDataSet(sql2);
            GridView2.DataBind();
            GridView3.DataSource = cs.accessGetDataSet(sql3);
            GridView3.DataBind();
            GridView4.DataSource = cs.accessGetDataSet(sql4);
            GridView4.DataBind();
            ...........
 if(Conn.State ==ConnectionState.Open )//如果还打开就关闭
        {
            Conn.Close();
        }

修改后

            OleDbConnection Conn = cs.Acce_Conn();
            string strSQL = "select * from dbs order by news_no desc ";
            DataSet ds = null;//定义DataSet ds

            if (Cache["cache_default"] == null)   //
            {
                ds = dbcenter.accessGetDataSet(strSQL);
                Cache.Insert("cache_default", ds, null, DateTime.Now.AddMinutes(60), TimeSpan.Zero);
            }
            ds = (DataSet)Cache["cache_default"];// 每次读取从cache获得,速度快
            
            DataView DV = ds.Tables[0].DefaultView;//获得表视图

            DataView dv1 = DV;
            DV.RowFilter = "inf_type='ok'";//用过滤rowfilter
            GridView1.DataSource = dv1;
            GridView1.DataBind();

            DataView dv2 = DV;
            DV.RowFilter = "inf_type='chinese'";
            GridView2.DataSource = dv2;
            GridView2.DataBind();

            DataView dv3 = DV;
            DV.RowFilter = "inf_type='english'";
            GridView3.DataSource = dv3;
            GridView3.DataBind();
.................
           
if(Conn.State ==ConnectionState.Open )//如果还打开就关闭
        {
            Conn.Close();
        }

//详细见default_hhh_school,特别感谢小西指导.

posted on 2009-08-17 09:34  pyman  阅读(265)  评论(0编辑  收藏  举报

导航