C#_数据访问类查询 和 属性扩展
public class Users { private string _UserName; /// <summary> /// 用户名 /// </summary> public string UserName { get { return _UserName; } set { _UserName = value; } } private string _PassWord; /// <summary> /// 密码 /// </summary> public string PassWord { get { return _PassWord; } set { _PassWord = value; } } private string _NickName; /// <summary> /// 昵称 /// </summary> public string NickName { get { return _NickName; } set { _NickName = value; } } private bool _Sex; /// <summary> /// 性别 /// </summary> public bool Sex { get { return _Sex; } set { _Sex = value; } } public string SexStr { get { return _Sex ? "男" : "女"; } } private DateTime _Birthday; /// <summary> /// 生日 /// </summary> public DateTime Birthday { get { return _Birthday; } set { _Birthday = value; } } public string BirthdayStr { get { return _Birthday.ToString("yyyy年MM月dd日"); } } private string _Nation; /// <summary> /// 民族 /// </summary> public string Nation { get { return _Nation; } set { _Nation = value; } } public string NationName { get { NationData Ndata = new NationData(); string end = Ndata.Select(_Nation); return end; } }
public List<Users> Select() { //泛型集合,放置所有Users数据对象 List<Users> list = new List<Users>(); cmd.CommandText = "select *from Users"; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows)//如果数据表中有数据 { while (dr.Read())//循环读取全部数据 { //没读取一行数据,就制作一个Users对象 Users u = new Users(); u.UserName = dr["UserName"].ToString(); u.PassWord = dr["PassWord"].ToString(); u.NickName = dr["NickName"].ToString(); u.Sex = Convert.ToBoolean(dr["Sex"]); u.Birthday = Convert.ToDateTime(dr["Birthday"]); u.Nation = dr["Nation"].ToString(); //注意,在循环中,将制作好的每一个对象,都放到集合中去 list.Add(u); } } conn.Close(); return list; }
public class NationData { SqlConnection conn = null; SqlCommand cmd = null; public NationData() { conn = new SqlConnection("server=.;database=Data0720;user=sa;pwd=123"); cmd = conn.CreateCommand(); } public string Select(string code) { string end = "<无>"; cmd.CommandText = "select *from Nation where NationCode=@a"; cmd.Parameters.Clear(); cmd.Parameters.Add("@a", code); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { dr.Read(); end = dr["NationName"].ToString(); } conn.Close(); return end; }
public class Nation { private string _NationCode; public string NationCode { get { return _NationCode; } set { _NationCode = value; } } private string _NationName; public string NationName { get { return _NationName; } set { _NationName = value; } } }