針對單條數據一般都是update語句直接更新
例如:update UserTable set UserName='小名' where userid=xxx
但是如果是針對List數據組進行更新的話不外乎兩種
1、程序for、foreach、while循環語句然后多次請求數據庫更新(這種在這里不多做解釋,因為基本上都知道這種方法)
2、重點說下下面這種方式:通過XML的方式在數據庫進行批量的更新
1、建立ListToXML方法
/// <summary>
/// 使用反射把List<T>轉換成XmlDocument
/// </summary>
/// <returns></returns>
public static XmlDocument ListToXML<T>(string XmlName,IList<T> IL)
{
try
{
XmlDocument XMLdoc = new XmlDocument();
//建立XML的定義聲明
XmlDeclaration XMLdec = XMLdoc.CreateXmlDeclaration("1.0", "utf-8", null);
XMLdoc.AppendChild(XMLdec);
XmlElement Root = XMLdoc.CreateElement(XmlName);
PropertyInfo[] PropertyInfos = typeof(T).GetProperties();
foreach (T item in IL)
{
XmlElement ChildNode = XMLdoc.CreateElement(typeof(T).Name);
foreach (PropertyInfo pro in PropertyInfos)
{
if (pro != null)
{
string KeyName = pro.Name;
string KeyValue = string.Empty;
if (pro.GetValue(item, null) != null)
{
KeyValue = pro.GetValue(item, null).ToString();
}
ChildNode.SetAttribute(KeyName,KeyValue);
ChildNode.InnerText = KeyValue;
}
}
Root.AppendChild(ChildNode);
}
XMLdoc.AppendChild(Root);
return XMLdoc;
}
catch(Exception ex)
{
//LogHelper.LogDebug("List<T>生成XML失敗:" + ex.Message);
return null;
}
}
2、將寫好的XMl直接當作參數@Data傳入存儲過程
public int UpdateAdminUsers(IList<AdminUserInfo> adminUsers)
{
SqlParameter[] param = new SqlParameter[1];
//拼接xml
string data = XMLHelper.ListToXML<AdminUserInfo>("AdminUserList", adminUsers).InnerXml.Replace("encoding=\"utf-8\"", "");
param[0] = new SqlParameter("@Data", data);
object o = SqlHelper.ExecuteScalar(DataHelper.ConnectionString, CommandType.StoredProcedure, "USP_AdminUsersUpdate", param);
return Convert.ToInt32(o);
}
3、數據庫的分析XMl然后進行數據的處理
Create PROCEDURE [dbo].[USP_AdminUsersUpdate]
@Data XML
AS
BEGIN
SET XACT_ABORT ON;
BEGIN TRANSACTION
DECLARE @RowCount AS INT=0;
DECLARE @AdminUserList TABLE(
[UserId] [int] NOT NULL,
[UserName] [nvarchar](50) NULL
);
INSERT @AdminUserList (UserId ,UserName )
SELECT T.c.value('@UserId','int') as UserId,
T.c.value('@UserName','nvarchar(50)') as UserName
FROM @Data.nodes('AdminUserList/AdminUserInfo') T(c);
INSERT dbo.AdminUser ( UserId , UserName )
SELECT UserId ,UserName FROM @AdminUserList;
SET @RowCount=@@ROWCOUNT;
COMMIT TRANSACTION
SELECT @RowCount AS RowsCount;
END
這種更新方式是將我們數據寫成XML有效避免了參數無限次的輸入