【发布时间】:2010-06-17 13:26:03
【问题描述】:
我正在使用 TableAdapter 在循环中的表中插入记录。
foreach(....)
{
....
....
teamsTableAdapter.Insert(_teamid, _teamname);
....
}
其中 TeamID 是表中的主键,_teamID 插入它。实际上我正在从包含唯一 teamId 的 XML 文件中提取数据
第一次运行此循环后,Insert 抛出 Duplicate Primary Key found 异常。为了解决这个问题,我已经这样做了
foreach(....)
{
....
....
try
{
_teamsTableAdapter.Insert(_teamid, _teamname);
}
catch (System.Data.SqlClient.SqlException e)
{
if (e.Number != 2627)
MessageBox.Show(e.Message);
}
....
....
}
但是使用try catch语句代价高,如何避免这个异常。我在 VS2010 中工作,INSERT ... ON DUPLICATE KEY UPDATE 不起作用。
我想避免使用 try catch 语句并在不使用 try catch 语句的情况下处理它。
【问题讨论】:
-
避免插入重复的主键。
标签: c# sql exception tableadapter