我正在尝试更新数据库。当我只添加一行时,它没有问题。但是,当我使用更改值的数据集更新数据库时,会出现错误:
`System.Data.DBConcurrencyException:并发冲突:UpdateCommand影响了预期Y记录的X.(抱歉荷兰。我会尽快找到错误的英文版。)
internal void updateDataSet(DataSet ds1)
{
using (SqlConnection _con = new SqlConnection("server=(local)\\SQLExpress;database=Alarmen;integrated Security=SSPI;"))
{
openConnection(_con);
log.Info("Database wordt geupdate");
try
{
var con = new SqlConnection(connectionString);
var adapter = new SqlDataAdapter("SELECT * FROM dbo.tbl_alarmen", con);
new SqlCommandBuilder(adapter);
//
// Fill the DataAdapter with the values in the DataTable.
//
adapter.Fill(ds1, "Alarmen");
//
// Open the connection to the SQL database.
//
//con.Open();
//
// Insert the data table into the SQL database.
//
adapter.Update(ds1, "Alarmen");
log.Info("Database geupdate van ds1");
}
catch (Exception err)
{
log.Info("Database updaten mislukt " + err);
}
//closeConnection(_con);
}
string sql = "SELECT * FROM tbl_alarmen";
SqlCommand _cmd;
SqlDataAdapter _dap;
internal void openConnection(SqlConnection _con)
{
log.Info("Database wordt geopend");
try
{
_con.Open();
}
catch (Exception ex)
{
log.Info("Database kon niet geopend worden " + ex);
}
}
internal void closeConnection(SqlConnection _con)
{
log.Info("Database wordt gesloten");
try
{
_con.Close();
}
catch (Exception ex)
{
log.Info("Database sluiten mislukt " + ex);
}
}
我知道尝试/捕获很奇怪。现在,我可以更容易地看到问题的显示位置。我会在发布前更改此内容。
我将提供有关填充数据表的代码的一些信息: 如果状态==活动,则表示它是新警报。在else语句中,这意味着它是一个需要更新状态的现有警报。
if (Status == "Active")
{
log.Info("Nieuw Alarm met " + AlarmName + " " + InstanceID + " " + Status + " " + VMSID);
DataRow dRow = ds1.Tables["Alarmen"].NewRow();
dRow[0] = ds1.Tables["Alarmen"].Rows.Count + 1;//Creating the primary key.
dRow[1] = VMSID;
dRow[2] = InstanceID;
dRow[3] = AlarmName;
dRow[4] = Priority;
dRow[5] = TriggerTime;
dRow[6] = Source;
dRow[7] = TriggerEvent;
dRow[8] = Status;
dRow[9] = AckType;
dRow[10] = AckBy;
dRow[11] = AckTime;
dRow[12] = CreationTimeStamp;
dRow[13] = PropagationLevel;
dRow[14] = AlarmRunningState;
dRow[15] = Destination;
dRow[16] = AlarmContext;
dRow[17] = AlarmGuid;
ds1.Tables["Alarmen"].Rows.Add(dRow);
interf.nieuwAlarm("Nieuw alarm ", dRow);
}
else
{
bool containTest = false;
log.Info("Status is not active " + Status);
for (int i = 0; i < ds1.Tables["Alarmen"].Rows.Count; i++)
{
DataRow dRow = ds1.Tables["Alarmen"].Rows[i];
string id = dRow[2].ToString();
string vms = dRow[1].ToString();
if (vms.Contains(VMSID) && id.Contains(InstanceID))
{
containTest = true;
dRow[8] = Status;
dRow[10] = AckBy;
dRow[11] = AckTime;
ds1.Tables["Alarmen"].Rows[i].ItemArray[8] = Status;
ds1.Tables["Alarmen"].Rows[i].ItemArray[10] = AckBy;
ds1.Tables["Alarmen"].Rows[i].ItemArray[11] = AckTime;
interf.changedAlarm("Veranderd alarm", dRow);
}
}
if (containTest == false)
{
log.Info("Onbekend Alarm is acknowledged " + InstanceID + " " + VMSID);
}
//Log er in zetten mocht het alarm niet voorkomen in de database
}
dc.updateDataSet(ds1);
at“dc.updateDataSet(ds1);”是类的声明,包含打开和更新数据库的代码。