private static void UpdatePersonBatch(List<PersonInfo> personInfoList, ILogger log)
{
string dbConnection = System.Environment.GetEnvironmentVariable("ConnectStr", EnvironmentVariableTarget.Process);
using (SqlConnection conn = new SqlConnection(dbConnection))
{
try
{
string[] nameArray = new string[]{"zhangsan", "lisi", "wangwu", "maliu"};
conn.Open();
log.LogInformation("=================================" + personInfoList.Count);
SqlDataAdapter sd = new SqlDataAdapter("SELECT id, name FROM Person WITH(NOLOCK) order by id ", conn);
DataSet datasets = new DataSet();
SqlCommandBuilder scb = new SqlCommandBuilder(sd);
sd.UpdateCommand = scb.GetUpdateCommand();
sd.UpdateCommand = new SqlCommand("UPDATE Person SET name=@name WHERE id=@id", conn);
sd.UpdateCommand.Parameters.Add("@id", SqlDbType.UniqueIdentifier, 3, "id");
sd.UpdateCommand.Parameters.Add("@name", SqlDbType.Char, 10, "name");
sd.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
sd.UpdateBatchSize = 0;
sd.Fill(datasets);
for (int i = 0; i < personInfoList.Count; i++)
{
datasets.Tables[0].Rows[i].BeginEdit();
datasets.Tables[0].Rows[i]["id"] = personInfoList[i].id;
log.LogInformation("=================================" + personInfoList[i].id);
datasets.Tables[0].Rows[i]["name"] = nameArray[i % 4];
log.LogInformation("=================================" + nameArray[i % 4]);
datasets.Tables[0].Rows[i].EndEdit();
}
sd.Update(datasets.Tables[0]);
datasets.Tables[0].Clear();
sd.Dispose();
datasets.Dispose();
}
catch (Exception e)
{
log.LogError(e.StackTrace.ToString());
}
finally
{
// データベースの接続终了
conn.Close();
}
}
}
出问题的地方是180行, sd.Update(datasets.Tables[0]);