/// param name="table">准备更新的DataTable新数据/param>
/// param name="TableName">对应要更新的数据库表名/param>
/// param name="primaryKeyName">对应要更新的数据库表的主键名/param>
/// param name="columnsName">对应要更新的列的列名集合/param>
/// param name="limitColumns">需要在SQL的WHERE条件中限定的条件字符串,可为空。/param>
/// param name="onceUpdateNumber">每次往返处理的行数/param>
/// returns>返回更新的行数/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)
{
//所有行设为修改状态
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];
//需要更新的列设置参数是,参数名为"@+列名"
for (int i = 0; i columnsName.Length; i++)
{
//此处拼接要更新的列名及其参数值
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);
//每次往返处理的行数
da.UpdateBatchSize = onceUpdateNumber;
result = da.Update(ds,TableName);
ds.AcceptChanges();
tran.Commit();
}
catch
{
tran.Rollback();
}
finally
{
sqlconn.Dispose();
sqlconn.Close();
}
}
return result;
}