ExecuteReader 获取数据集的基础使用
/// <summary> /// 获取多个结果集 /// </summary> /// <param name="sql"></param> /// <returns></returns> /// <exception cref="Exception"></exception> public static SqlDataReader GetReader(string sql, params SqlParameter[] parse) { SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand(sql, conn); try { conn.Open(); cmd.Parameters.Clear(); cmd.Parameters.AddRange(parse); return cmd.ExecuteReader(CommandBehavior.CloseConnection); }catch (Exception ex) { conn.Close(); throw new Exception(ex.Message); } }
//获取班级列表 /// <summary> /// StudentClass 这是我定义的实体类 /// SqlHelper.GetReader() 方法是我定义的 SqlHelper数据库访问类 /// </summary> /// <returns></returns> public List<StudentClass> GetStudentClasses() { string sql = "select * from StudentClass"; List<StudentClass> students = new List<StudentClass>(); SqlDataReader sqlData = SqlHelper.GetReader(sql); while (sqlData.Read()) { students.Add(new StudentClass() { ClassId = Convert.ToInt32(sqlData["ClassId"]), ClassName = sqlData["ClassName"].ToString() }) ; } return students ; }
public class StudentClass { public int ClassId { get; set; } public string ClassName { get; set; } }