/// param name="table">準備更新的DataTable新數(shù)據(jù)/param>
/// param name="TableName">對應要更新的數(shù)據(jù)庫表名/param>
/// param name="primaryKeyName">對應要更新的數(shù)據(jù)庫表的主鍵名/param>
/// param name="columnsName">對應要更新的列的列名集合/param>
/// param name="limitColumns">需要在SQL的WHERE條件中限定的條件字符串,可為空。/param>
/// param name="onceUpdateNumber">每次往返處理的行數(shù)/param>
/// returns>返回更新的行數(shù)/returns>
public static int Update(DataTable table, string TableName, string primaryKeyName, string[] columnsName, string limitWhere,int onceUpdateNumber)
{
if (string.IsNullOrEmpty(TableName)) return 0;
if (string.IsNullOrEmpty(primaryKeyName)) return 0;
if (columnsName == null || columnsName.Length = 0) return 0;
DataSet ds = new DataSet();
ds.Tables.Add(table);
int result = 0;
using (SqlConnection sqlconn = new SqlConnection(SqlHelper.ConnString))
{
sqlconn.Open();
//使用加強讀寫鎖事務
SqlTransaction tran = sqlconn.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
foreach (DataRow dr in ds.Tables[0].Rows)
{
//所有行設為修改狀態(tài)
dr.SetModified();
}
//為Adapter定位目標表
SqlCommand cmd = new SqlCommand(string.Format("select * from {0} where {1}", TableName,limitWhere), sqlconn, tran);
SqlDataAdapter da = new SqlDataAdapter(cmd);
SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(da);
da.AcceptChangesDuringUpdate = false;
string columnsUpdateSql = "";
SqlParameter[] paras = new SqlParameter[columnsName.Length];
//需要更新的列設置參數(shù)是,參數(shù)名為"@+列名"
for (int i = 0; i columnsName.Length; i++)
{
//此處拼接要更新的列名及其參數(shù)值
columnsUpdateSql += ("[" + columnsName[i] + "]" + "=@" + columnsName[i] + ",");
paras[i] = new SqlParameter("@" + columnsName[i], columnsName[i]);
}
if (!string.IsNullOrEmpty(columnsUpdateSql))
{
//此處去掉拼接處最后一個","
columnsUpdateSql = columnsUpdateSql.Remove(columnsUpdateSql.Length - 1);
}
//此處生成where條件語句
string limitSql = ("[" + primaryKeyName + "]" + "=@" + primaryKeyName);
SqlCommand updateCmd = new SqlCommand(string.Format(" UPDATE [{0}] SET {1} WHERE {2} ", TableName, columnsUpdateSql, limitSql));
//不修改源DataTable
updateCmd.UpdatedRowSource = UpdateRowSource.None;
da.UpdateCommand = updateCmd;
da.UpdateCommand.Parameters.AddRange(paras);
da.UpdateCommand.Parameters.Add("@" + primaryKeyName, primaryKeyName);
//每次往返處理的行數(shù)
da.UpdateBatchSize = onceUpdateNumber;
result = da.Update(ds,TableName);
ds.AcceptChanges();
tran.Commit();
}
catch
{
tran.Rollback();
}
finally
{
sqlconn.Dispose();
sqlconn.Close();
}
}
return result;
}