利用對象來更新資料 UpdateData(object o),updatedataobject
<1>
/// <summary> /// DAL層 /// </summary> public class UserInfoService { /// <summary> /// 根據使用者名稱查詢資料,將查詢出來的資料轉換成一個list (將資料庫裡的資料表T_User映射到實體類UserInfo) /// </summary> /// <param name="userName">使用者名稱</param> /// <returns></returns> public static List<UserInfo> SelectDataToEntity(string userName) { List<UserInfo> list = SqlHelper.SelectDataToList<UserInfo>("select * from T_User where UserName=@username", new SqlParameter("username", userName)); return list; } /// <summary> /// 更新資料到資料庫 /// </summary> /// <param name="u">一個實體類對象</param> /// <returns></returns> public static int UpdateDate(UserInfo u) { string sql = "update T_User set UserName=@userName,Password=@pwd,Email=@email,Age=@age,Gender=@gender,State=@state,VCode=@VCode where UserId=@uid"; return SqlHelper.ExecuteNonQuery(sql, new SqlParameter("@userName",u.UserName), new SqlParameter("@pwd",u.Password), new SqlParameter("@email",u.Email), new SqlParameter("@age",u.Age), new SqlParameter("@gender",u.Gender), new SqlParameter("@state",u.State), new SqlParameter("@vcode",u.VCode), new SqlParameter("@uid", u.UserId) ); } }}
<2>
/// <summary> /// BLL層 /// </summary> public class ResetPwd : IHttpHandler { /// <summary> /// 根據使用者名稱查詢出當前這條資料(其實這條資料就是一個對象) /// </summary> /// <param name="context">使用者名稱</param> public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; string username = context.Request["UserName"]; string pwd = context.Request["newPassword"]; List<UserInfo> list = UserInfoService.SelectDataToEntity(username); //因為查詢出來的是一個list,所以這裡取得這個list的第一條資料(有且只能有一條) UserInfo u = list.Single(); u.Password = pwd; //這裡你可以將你要更新的欄位賦新值。這裡我僅僅是更新密碼,當然你也可以跟新其他的。 //u.Email = newEmail; 可以跟新郵箱(樣本) //u.Age = newAge; 可以跟新年齡(樣本) //調用DAL層中的 DataUpdate()方法,將這個UserInfo對象u作為參數傳遞過去,來將資料更新到資料庫。 UserInfoService.UpdateDate(u); }
Model
UserInfo類
using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace Model{ public class UserInfo { public int UserId { get; set; } public string UserName { get; set; } public string Email { get; set; } public string Password { get; set; } public int Age { get; set; } public int Gender { get; set; } public int State { get; set; } public Guid VCode { get; set; } }}