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 [email protected]"; 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 [email protected]"; 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(); } } }
时间: 2024-10-09 04:41:52