ado.net 学习 02 ExecuteReader()方法和DataReader

重点关注:

1.  SqlDataReader reader = cmd.ExecuteReader();

  --执行ExecuteReader()方法,将数据放在 SqlDataReader类型的reader中。

2.  StringBuilder htmlStr = new StringBuilder("");

  --建立 StringBuilder类型的htmlStr。

3.  while (reader.Read())   {}

  --循环读取数据,

4.  htmlStr.Append(reader.GetInt32(0).ToString());

  --基于循环,将数据放在StringBuilder类型的htmlStr中。

5.  HtmlContent.Text = htmlStr.ToString();

  --将htmlStr值转换为string,并传给Literal控件。

6.  Literal控件的使用??

  --

 

1     <div>
2         <h2>Employees</h2>
3         <asp:Literal runat="server" ID="HtmlContent" />
4     </div>

 

 1  protected void Page_Load(object sender, EventArgs e)
 2         {
 3             // Create the Command and the Connection.
 4             string connectionString =
 5                 WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString;
 6 
 7             SqlConnection con = new SqlConnection(connectionString);
 8             string sql = "SELECT * FROM Employees";
 9             SqlCommand cmd = new SqlCommand(sql, con);
10 
11             // Open the Connection and get the DataReader.
12             con.Open();
13             SqlDataReader reader = cmd.ExecuteReader();
14 
15             // Cycle through the records, and build the HTML string.
16             StringBuilder htmlStr = new StringBuilder("");
17             while (reader.Read())
18             {
19                 htmlStr.Append("<li>");
20                 htmlStr.Append(reader["TitleOfCourtesy"]);
21                 htmlStr.Append(" <b>");
22                 htmlStr.Append(reader.GetString(1));
           //测试证明:reader.GetString()方法,其中的数字从0开始,代表所取表中的第1列。如下图结果中右图所示 
23 //htmlStr.Append(reader.GetInt32(0).ToString()); 24 htmlStr.Append("</b>, "); 25 htmlStr.Append(reader.GetString(2)); 26 htmlStr.Append(" - employee from "); 27 htmlStr.Append(reader.GetDateTime(6).ToString("d")); 28 htmlStr.Append("</li>"); 29 } 30 31 // Close the DataReader and the Connection. 32 reader.Close(); 33 con.Close(); 34 35 // Show the generated HTML code on the page. 36 HtmlContent.Text = htmlStr.ToString(); 37 }

运行结果:

 

 

 

posted @ 2013-05-21 23:01  罗汉果  阅读(345)  评论(0编辑  收藏  举报