2012-11-15 35 views
1

這是我的aspx代碼,當我只想獲取一條記錄時。Mysql + aspx - 如何使用閱讀器填充數組

  conn = new SqlConnection(cs); 
      string sql = "SELECT * FROM [school_database].[arrest_school].[registration_allstudent] where RegistrationId='llts4da2'"; 
      SqlCommand cmd = new SqlCommand(sql, conn); 
      conn.Open(); 
      reader = cmd.ExecuteReader(); 
      reader.Read(); 
      Model.Registration regis = new Model.Registration(); 
      regis.Address = reader["Address"].ToString(); 
      return regis; 

現在我想獲取所有記錄並返回註冊數組。怎麼做。 我知道如何計算讀取的行數,然後如何填充它的regis數組。 雷吉斯有5場...地址,城市,姓名,班級,PHONENO

回答

0

要閱讀所有的記錄,一個辦法是這樣的:

using(IDataReader reader = cmd.ExecuteReader()) 
{ 
    List<Registration> result = new List<Registration>(); 
    while(reader.Read()) 
    { 
     result.Add(new Registration{Address=reader["Address"].ToString()}); 
    } 
    return result; 
} 

另一種方法是這樣的:

DataTable t = new DataTable(); 
t.Load(cmd.ExecuteReader); 
var result = from c in t.AsEnumerable() 
       select new Registration{Address=c.Field<string>("Address")}; 
return result.ToList(); 
0
  int i = 0; 
      Model.Registration regis = new Model.Registration(); 
      if (reader.HasRows) 
      { 
       do 
       { 
        i++; 
        regis.Address = regis.Address + reader["Address"].ToString(); 
       } while (reader.Read()); 
      } 
      regis.Address = i.ToString() + " " + regis.Address; 
      return regis; 

我正在尋找更簡單的方法...這也幫助