1

当我只想获取一条记录时,这是我的 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 数组。怎么做。我知道如何计算 read 中的行,然后如何填充它 regis 数组。Regis 有 5 个字段...地址、城市、姓名、班级、电话号码

4

2 回答 2

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();
于 2012-11-15T16:32:48.640 回答
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;

我正在寻找一种更简单的方法......这也有帮助

于 2012-11-16T17:12:15.613 回答