SqlDataReader的用法

datareader对象提供只读单向数据的快速传递,单向:您只能依次读取下一条数据;只读:DataReader中的数据是只读的,不能修改;相对地,DataSet中的数据可以任意读取和修改.

它有一个很重要的方法,是Read,是个布尔值,作用是前进到下一条数据,一条条的返回数据,当布尔值为真时执行,为假时跳出。如

while(dr.Read())

{

     Response.write(dr["UserName"]

}

dr.close();

以下是用户登录判断时候合法用户的代码

SqlConnection con = DB.WebConnection();//通过类调用连接上数据库

          con.Open();//打开连接

          SqlCommand com = new SqlCommand();

          com.CommandText = "Select * from Users where UserName='" + tbUserName.Text + "'";

          com.CommandType = CommandType.Text;

          com.Connection = con;

          SqlDataReader reader = com.ExecuteReader();

         if (reader.Read())

        {

            

             int UserID = reader.GetInt32(0);

             string Password = reader["UserPassword"].ToString();

             string Password0 = tbUserPassword.Text;

             if (Password == Password0)

            {

                  Session["uid"] = UserID;

                  Session["name"] =tbUserName.Text;

                  Response.Redirect("index.aspx");

              }

             else

            {

                  Response.Redirect("login.aspx");

              }

          }

         else

        {

              Response.Redirect("login.aspx");

          }

用这种方法不仅能判断用户名是否合法,还可以很方便地获取更多关于该用户的信息,其中,我比较喜欢用的是string Password = reader["UserPassword"].ToString();这种方法,但是这种方法似乎不能获取int类型的字段数据,比如这里的UserId,只能用int UserID = reader.GetInt32(0);这种方法获取它的值。不知道用字段名有没有方法获取到UserId的值。

多个datareader结合使用可以实现简单的主从表数据查询,不过这种做法应该不算是好的做法。。

posted @ 2008-06-30 15:48  xumingming  阅读(7814)  评论(3编辑  收藏  举报