首页 > 代码库 > 数据访问类查询
数据访问类查询
public class UsersData { SqlConnection conn = null; SqlCommand cmd = null; public UsersData() { conn = new SqlConnection("server=.;database=Data0720;user=sa;pwd=123"); cmd = conn.CreateCommand(); } /// <summary> /// Users表添加方法 /// </summary> /// <param name="u">要添加到数据库的Users对象</param> public void Insert(Users u) { cmd.CommandText = "insert into Users values(@a,@b,@c,@d,@e,@f)"; cmd.Parameters.Clear(); cmd.Parameters.Add("@a", u.UserName); cmd.Parameters.Add("@b", u.PassWord); cmd.Parameters.Add("@c", u.NickName); cmd.Parameters.Add("@d", u.Sex); cmd.Parameters.Add("@e", u.Birthday); cmd.Parameters.Add("@f", u.Nation); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } public Users Select(string Uname) { Users u = null; cmd.CommandText = "select *from Users where UserName=@a"; cmd.Parameters.Clear(); cmd.Parameters.Add("@a", Uname); conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) { dr.Read(); 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(); } conn.Close(); return u; } public bool Delete(string Uname) { bool delOK = false; cmd.CommandText = "delete from Users where UserName =@a"; cmd.Parameters.Clear(); cmd.Parameters.Add("@a", Uname); conn.Open(); try { cmd.ExecuteNonQuery(); delOK = true; } catch { } conn.Close(); return delOK; } 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 void Select1() { cmd.CommandText = "select *from Users"; conn.Open(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows)//如果数据表中有数据 { while (dr.Read())//循环读取全部数据 { Console.WriteLine(dr["UserName"] + " " + dr["PassWord"]); } } conn.Close(); } }}
数据访问类查询
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。