编写数据库增、删、改操作方法
提示: 作者被禁止或删除 内容自动屏蔽
//得到所有用户列表 public IList<Users> getAllUsers() { string sql = "select users.*,u.unitName,R.* from Users as users left join Unit as u on users.unitId = u.id left join Roles R on users.roleId = R.id"; IList<Users> list = new List<Users>(); using (SqlDataReader reader = DBHelper.ExecuteReader(sql)) { while (reader.Read()) { Users model = new Users(); model.Id = Convert.ToInt32(reader["Id"]); model.Account = reader["Account"].ToString(); model.Password = reader["Password"].ToString(); model.Username = reader["Username"].ToString(); model.Telephone = reader["Telephone"].ToString(); model.Unitid = Convert.ToInt32(reader["unitId"]); model.Roleid = (int)reader["Roleid"]; Unit unit = new Unit(); unit.UnitName = reader["unitName"].ToString(); model.Unit = unit; Roles role = new Roles(); role.Role = reader["role"].ToString(); role.Power = reader["power"].ToString(); model.Role = role; list.Add(model); } } return list; } /// <summary> /// 添加用户 /// </summary> /// <param name="user"></param> /// <returns></returns> public int AddUser(Users user) { string sql = "insert into Users (account, password, username, telephone, unitid, roleid)" + " values (@account, @password, @username, @telephone, @unitid, @roleid)"; sql += " ; SELECT @@IDENTITY"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@account", user.Account), new SqlParameter("@password", user.Password), new SqlParameter("@username", user.Username), new SqlParameter("@telephone", user.Telephone), new SqlParameter("@unitid", user.Unit), new SqlParameter("@roleid", user.Roleid) }; int newId = 0; newId = DBHelper.ExecuteScalar(sql, para); return newId; } /// <summary> /// 更新密码 /// </summary> public int UpdatePwd(int id, string pwd) { string strsql = "update users set password='" + pwd + "' where id= " + id; int i = Convert.ToInt32(DBHelper.ExecuteCommand(strsql.ToString())); return i; } //根据用户id 删除用户 public int DeleteUser(int id) { string sql = "delete from users where id=" + id; int newId = 0; newId = DBHelper.ExecuteScalar(sql); return newId; }