【IT168技術(shù)文檔】
datareader對(duì)象提供只讀單向數(shù)據(jù)的快速傳遞,單向:您只能依次讀取下一條數(shù)據(jù);只讀:DataReader中的數(shù)據(jù)是只讀的,不能修改;相對(duì)地,DataSet中的數(shù)據(jù)可以任意讀取和修改. 它有一個(gè)很重要的方法,是Read,是個(gè)布爾值,作用是前進(jìn)到下一條數(shù)據(jù),一條條的返回?cái)?shù)據(jù),當(dāng)布爾值為真時(shí)執(zhí)行,為假時(shí)跳出。如 while(dr.Read()) { Response.write(dr["UserName"] } dr.close(); 以下是用戶(hù)登錄判斷時(shí)候合法用戶(hù)的代碼 SqlConnection con = DB.WebConnection();//通過(guò)類(lèi)調(diào)用連接上數(shù)據(jù)庫(kù) con.Open();//打開(kāi)連接 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"); } 用這種方法不僅能判斷用戶(hù)名是否合法,還可以很方便地獲取更多關(guān)于該用戶(hù)的信息,其中,我比較喜歡用的是string Password = reader["UserPassword"].ToString();這種方法,但是這種方法似乎不能獲取int類(lèi)型的字段數(shù)據(jù),比如這里的UserId,只能用int UserID = reader.GetInt32(0);這種方法獲取它的值。不知道用字段名有沒(méi)有方法獲取到UserId的值。 |
|