前面一節中已經實現了簡單的新增功能,下面來實現修改功能,代碼如下1-1:
#region 將實體數據修改到數據庫
public int Update<T>(T entity)
{
TableInfo tableInfo = DbEntityUtils.GetTableInfo (entity,DbOperateType.UPDATE);
string strSql = DbEntityUtils.GetUpdateSql(tableInfo);
IDbDataParameter[] parms = DbFactory.CreateDbParameters (tableInfo.Columns.Count);
DbEntityUtils.SetParameters(tableInfo.Columns, parms);
object val = AdoHelper.ExecuteNonQuery(transaction, CommandType.Text, strSql, parms);
return Convert.ToInt32(val);
}
#endregion
在1-1代碼中,絕大多數代碼都和前面一節中的Save方法相同,這裡主要看一下string strSql = DbEntityUtils.GetUpdateSql(tableInfo); 這段代碼1-2:
public static string GetUpdateSql(TableInfo tableInfo)
{
StringBuilder sbBody = new StringBuilder();
foreach (string key in tableInfo.Columns.Keys)
{
object value = tableInfo.Columns[key];
sbBody.Append(key).Append("=").Append(AdoHelper.DbParmChar + key).Append(",");
}
sbBody.Remove(sbBody.ToString().Length - 1, 1);
tableInfo.Columns.Put(tableInfo.Id.Key, tableInfo.Id.Value);
string strSql = "update {0} set {1} where {2} =" + AdoHelper.DbParmChar + tableInfo.Id.Key;
strSql = string.Format(strSql, tableInfo.TableName, sbBody.ToString(), tableInfo.Id.Key);
return strSql;
}
上面代碼就是通過tableInfo.Columns集合中的列名,組合成字符串,如strSql = “update student set studentno = @studentno,name = @name,sex = @sex where studentid = @studentid”; 然後在Update方法中通過參數數組將值傳入並作更新操作。