我正在尝试使用数据集来更新SQL数据库,我试图在数据集中使用foreach,如果该元素已经在数据库中捕获错误并继续到下一个,但错误总是相同的:
“System.Data.SqlClient.SqlException(0x80131904):违反PRIMARY KEY约束'PK_share1'。无法在对象中插入重复键 'dbo.share1'。重复键值为(4008)。“
我不明白为什么这个foreach总是在试图只插入数据集的1个元素而不是继续并找到一个新元素
if (changes != null)
{
foreach (DataRow row in changes.Tables[0].Rows)
{
try{
adapter.Update(changes);
Console.WriteLine("Changes Done");}
catch(Exception ex){
Console.WriteLine(ex.ToString());
continue;
}
}
}
我也尝试过:
if (changes != null)
{
foreach (DataTable table in changes.Tables)
{
try{
adapter.Update(changes);
Console.WriteLine("Changes Done");}
catch(Exception ex){
Console.WriteLine(ex.ToString());
continue;
}
}
}
答案 0 :(得分:0)
在第一个代码中,您将遍历行,但每次更新整个DataSet。如果您想更新DataSet,那么您不需要多次这样做。
if (changes != null)
{
try
{
adapter.Update(changes);
Console.WriteLine("Changes Done");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
在第二段代码中,您正在迭代表,但更新整个DimSet。要逐个更新表格,您应该拨打adapter.Update(table);
而不是adapter.Update(changes);
。
if (changes != null)
{
foreach (DataTable table in changes.Tables)
{
try
{
adapter.Update(table);
Console.WriteLine("Changes Done");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
continue;
}
}
}