How do I connect to a database and loop over a recordset in C#?

前端 未结 8 2150
孤独总比滥情好
孤独总比滥情好 2021-01-03 17:44

What\'s the simplest way to connect and query a database for a set of records in C#?

相关标签:
8条回答
  • 2021-01-03 18:21

    If you are intending on reading a large number of columns or records it's also worth caching the ordinals and accessing the strongly-typed methods, e.g.

    using (DbDataReader dr = cmd.ExecuteReader()) {
      if (dr.Read()) {
        int idxColumnName = dr.GetOrdinal("columnName");
        int idxSomethingElse = dr.GetOrdinal("somethingElse");
    
        do {
          Console.WriteLine(dr.GetString(idxColumnName));
          Console.WriteLine(dr.GetInt32(idxSomethingElse));
        } while (dr.Read());
      }
    }
    
    0 讨论(0)
  • 2021-01-03 18:21

    I guess, you can try entity framework.

    using (SchoolDBEntities ctx = new SchoolDBEntities())
    {
         IList<Course> courseList = ctx.GetCoursesByStudentId(1).ToList<Course>();
         //do something with courselist here
    }
    
    0 讨论(0)
提交回复
热议问题