尝试通过SqlDataAdapter.Update(DataTable)
更新数据表时,我收到ArgumentOutOfRangeException“StatementType枚举值4无效”。根据{{3}},可能的枚举值是Select,Insert,Update,Delete和Batch,我猜测Batch是值4。
我不确定如何设置此值,因为它属于我在SqlRowUpdatedEventHandler中获取的SqlRowUpdatedEventArgs对象,或者它为何无效。
基本上我正在从Web服务调用返回的XmlNode构建DataTable,对数据视图进行排序,然后以200的批量发布更新。
XmlNode result = null;
using (LeadService.ClientService service = new LeadService.ClientService())
{
const string UserName = "SomeUserName";
const string Password = "SomePassword";
const int ChildReportId = 746;
result = service.GetReportResults(UserName, Password, ChildReportId, null);
}
if (result.InnerXml != "")
{
DataTable leads = new DataTable();
leads.Columns.Add("ID1", typeof(int));
leads.Columns.Add("ID2", typeof(string));
leads.Columns.Add("CREATEDDATE", typeof(DateTime));
foreach (XmlNode n in result.ChildNodes)
{
DataRow row = leads.NewRow();
row["ID1"] = n["Id1"].InnerText;
row["ID2"] = n["Id2"].InnerText;
row["CREATEDDATE"] = n["DateAdded"].InnerText;
leads.Rows.Add(row);
}
leads.DefaultView.Sort = "CREATEDDATE";
DataTable newTable = leads.DefaultView.ToTable();
newTable.AcceptChanges();
foreach (DataRow r in newTable.Rows)
{
r.SetModified();
}
const string Update = "UPDATE SOMETHING SET ID1 = @ID1 WHERE ID2 = @ID2";
using (SqlConnection con = new SqlConnection(Dal.GetConnectionString("CONNECTIONSTRING")))
{
SqlDataAdapter adap = new SqlDataAdapter();
adap.UpdateCommand = new SqlCommand(Update);
adap.UpdateCommand.Parameters.Add("@ID1", SqlDbType.NVarChar, 75, "ID1");
adap.UpdateCommand.Parameters.Add("@ID2", SqlDbType.VarChar, 18, "ID2");
adap.UpdateCommand.UpdatedRowSource = UpdateRowSource.None;
adap.UpdateBatchSize = 200;
adap.RowUpdated += new SqlRowUpdatedEventHandler(adap_RowUpdated);
adap.Update(newTable);
}
}
这是事件处理程序:
private static void adap_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
_rowsProcessed += e.RowCount;
_recordsAffected += e.RecordsAffected;
}
答案 0 :(得分:1)
卫生署!我没有在SqlCommand对象中设置连接!不确定奇怪错误背后的原因,但更改构造函数重载清除了一切:
using (SqlConnection con = new SqlConnection(Dal.GetConnectionString("CONNECTIONSTRING")))
{
SqlDataAdapter adap = new SqlDataAdapter();
adap.UpdateCommand = new SqlCommand(Update, con);
// ...
adap.Update(newTable);
}
答案 1 :(得分:0)
可能会认为您添加行而不是更新。尝试将SetModified
移动到循环中:
foreach (XmlNode n in result.ChildNodes)
{
DataRow row = leads.NewRow();
row["ID1"] = n["Id1"].InnerText;
row["ID2"] = n["Id2"].InnerText;
row["CREATEDDATE"] = n["DateAdded"].InnerText;
leads.Rows.Add(row);
row.SetModified();
}