代码整理——GridView,计时,链接MSSQL,Lucene.net的检索和建立索引

来源:互联网 发布:python 解压war文件 编辑:程序博客网 时间:2024/05/17 18:11

关于GridView的使用

前台:

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None" Height="145px" OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5" Width="894px">
涉及数据显示的关键代码

AllowPaging="true"——允许分页;

OnPageIndexChanging="GridView1_PageIndexChanging"——在后台编写代码实现GridView1_PageIndexChanging,用来实现数据绑定;

PageSize="5"——每页显示5行数据,默认为10;

后台:

protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e){        GridView1.PageIndex = e.NewPageIndex;        this.Button2_Click(sender, e);    }

创建记录结果集:

DataTable Results = new DataTable();    private void setTable()    {        //定义字段,作为GridView表头显示在页面上        this.Results.Columns.Add("title", typeof(string));        this.Results.Columns.Add("info", typeof(string));    }

Button2_Click()中,先进行数据获取,数据处理等操作,再进行GridView绑定,本文是用Lucene进行索引检索获得数据结果。

for (int i = 0; i <= hit.Length() - 1; i++){Document doc = hit.Doc(i);DataRow row = Results.NewRow();row["title"] = doc.Get("title");row["info"] = doc.Get("content");this.Results.Rows.Add(row);}GridView1.DataSource = Results;GridView1.DataBind();

关于计时,比较简单

DateTime dt = DateTime.Now;//开始记时
TimeSpan ts = System.DateTime.Now.Subtract(dt); //计算用时。
Response.Write("<font color=red>ts.ToString() + " 毫秒  ..<br>");//显示用时结果
其中Now.Substract(dt)——表示从Now这个DateTime对象中,减去指定的时间和日期dt

关于连接MSSQL

string conn = "Server=C;DataBase=db_res;Uid=sa;pwd=;";using (SqlConnection con = new SqlConnection(conn)){SqlDataAdapter dap = new SqlDataAdapter("select * from tb_res", con);DataSet ds = new DataSet();dap.Fill(ds);}

ds.Tables[0].Rows[0]——表示获得结果的第一行数据

ds.Tables[0].Rows[0][0]——表示获得结果的第一行数据的第一列元素内容

关于Lucene.net建立索引

Lucene.Net.Analysis.Standard.StandardAnalyzer a = new Lucene.Net.Analysis.Standard.StandardAnalyzer();//创建分析器IndexWriter iw = new IndexWriter(Server.MapPath("Index"), a, true);//创建索引对象,获得索引结果存入Index文件夹中try{Document doc = new Document();doc.Add(new Field("info", info, Field.Store.YES, Field.Index.TOKENIZED));doc.Add(new Field("title", title, Field.Store.YES, Field.Index.TOKENIZED));//较低的Lucene.net版本中,这两句话写作//doc.Add(Field.Text("info", info));//doc.Add(Field.Text("title", title));iw.AddDocument(doc);}catch (Exception ex){}iw.Optimize();  //优化索引iw.Close();     //关闭索引

关于Lucene.net基于索引的单条件单字段检索

Lucene.Net.Search.IndexSearcher search = new Lucene.Net.Search.IndexSearcher(Server.MapPath("Index")); //把刚才建立的索引取出来QueryParser parser = new QueryParser("info", new StandardAnalyzer());Query q = parser.Parse(txtKey.Text);//txtKey.txt为前台文本框中,用户要求检索的内容Lucene.Net.Search.Hits hit = search.Search(q);//Hits对象hit中存在若干条document类的对象,通过hit.doc(),以及doc.get()即可获得索引中的内容search.Close();

体会:先建立索引在进行索引,确实有效的减少了数据库访问次数,提高效率的同时,也提高了数据库的安全性。如果服务器上存在的索引数据被破坏,即可通过重新建立索引的方式恢复,而无需担心数据库的内容遭到破坏。





原创粉丝点击