如何在C#中从数据库中将项添加到列表<object>?

时间:2015-10-16 10:02:16

标签: c# list object

我正在创建list <object>,我在这里添加数据库中的数据。

但我完全不知道如何处理list <object>

public class ClassList
{
    public int Name { get; set; }
    public string Birthday { get; set; }
}

private void GetClassList()
{
    SqlConnection conn = new SqlConnection(GlobalVar.ConnString);
    SqlCommand cmd = new SqlCommand
        ("SELECT * " +
         "FROM Class_Data ", conn);
    conn.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    try
    {
        List<ClassList> ClassList = new List<ClassList>();
        while (dr.Read())
        {
            ClassList.Add(new ClassList()
            {
                Name = ___?___, //what should i write here
                Birthday = ___?___ //and here
            });
        }
     }
    catch{}
    finally
    {
        dr.Close();
        conn.Close();
    }
}

一直在寻找大量信息但仍无法解决问题。

如果有人可以提供帮助,我将非常感激!

4 个答案:

答案 0 :(得分:2)

这应该这样做:

List<ClassList> ClassList = new List<ClassList>();
        while (dr.Read())
        {
            ClassList.Add(new ClassList()
            {
                Name = (int)dr["Name"], //the name of the db column
                Birthday = dr["Birthday"].ToString();
            });
        }

作为旁注,从可读性/维护的角度来看,可能值得将您的查询从SELECT *...更改为仅选择所需的列。

另外,Name真的int似乎可能是string

您还可以参考文档:

SqlDataReader.Item Property (String)

答案 1 :(得分:0)

您可以使用数据库查询返回的列名称dr

dr["ColumnName"]
 ClassList.Add(new ClassList()
 {
         Name = dr["NameColum"], //what should i write here
         Birthday = dr["BrithColum"] //and here
 });

答案 2 :(得分:0)

类似的东西:

// You don't use "this" in the context
// It seems, that you want to return the collected data (List<ClassList>)
private static List<ClassList> GetClassList() {
  // Put IDisposable into using 
  using (SqlConnection conn = new SqlConnection(GlobalVar.ConnString)) {
    conn.Connect();

    // You want to fetch two fields only, right? Not the entire table (*)
    String sql = 
      @"select Name,
               BirthDay
          from Class_Data"

    using (SqlCommand cmd = new SqlCommand(sql, conn)) {
      List<ClassList> result = new List<ClassList>();

      using (SqlDataReader dr = cmd.ExecuteReader()) {
        while (dr.Read()) {
          result.Add(new ClassList() {
            Name = Convert.ToString(dr[0]),
            Birthday = Convert.ToDateTime(dr[1])
          });
        }
      }  

      return result;  
    }  
  }
}

答案 3 :(得分:0)

您可以使用dr["ColumnName"]访问列值。