DataReader的例子
前:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="DataReader对象.aspx.cs" Inherits="WebApplication1.DataReader对象" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table border="1" cellpadding="0" cellspacing="0"> <tr><td>编号</td><td>账号</td><td>真实姓名</td><td>年龄</td><td> 性别</td><td>手机</td><td>电话</td><td>电子邮件</td></tr> <% ShowData(); %> </table> </div> </form> </body> </html>
后台Cs:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace WebApplication1 { public partial class DataReader对象 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public void ShowData() { SqlConnection conn = new SqlConnection(@"server=Rose-PC\SQLEXPRESS;Database=User;User Id=sa;password="); SqlCommand command =new SqlCommand("Select * from UserInfo where Sex=1",conn); conn.Open(); //得到DataReader的实例 注意:使用CommandBehavior这个参数 //以便同时关闭Connection SqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection); //如果当前记录还有下一条记录,则循环不会终止 while (reader.Read()) { //按着列顺序和对应类型直接读取值 Response.Write("<tr><td>" + reader.GetInt32(0) + "</td>"); Response.Write("<td>" + reader.GetString(1) + "</td>"); Response.Write("<td>" + reader.GetString(2) + "</td>"); Response.Write("<td>" + reader.GetByte(3) + "</td>"); //下面是按着列顺序直接读取值,并且根据值来判断最终显示结果 Response.Write("<td>" + (reader.GetBoolean(4)==true?"男":"女" )+ "</td>"); //按着列顺序读取,列的值需要做相应的转换 Response.Write("<td>" + reader[5].ToString() + "</td>"); Response.Write("<td>" + reader["Phone"] + "</td>"); Response.Write("<td>" + reader["Email"].ToString() + "</td></tr>\n"); } reader.Close(); } } }
显示的图片: