如何在C#中添加记录时处理数据表中的唯一约束异常 [英] How to handle unique constraint exception in datatable while adding record in C#
问题描述
我像这样向数据表添加了唯一约束
I have added unique constraint to datatable like this
DataTable dtemp
private void TempTable()
{
dtemp = new DataTable("Temp");
dtemp.Columns.Add(new DataColumn("Table", typeof(int)));
dtemp.Columns.Add(new DataColumn("Capacity", typeof(int)));
UniqueConstraint TableUnique = new UniqueConstraint(new DataColumn[] { dtemp.Columns["Table"] });
dtemp.Constraints.Add(TableUnique);
}
当我尝试添加相同的记录时,它不会去捕获块,而是会突然退出程序并在 Visual Studio 中给出唯一约束未处理的异常.
When I try to add same record, instead of going to catch block, it simply exit the program abruptly and gives unique constraint unhandled exception in the visual studio.
private void GetTable()
{
try
{
dtemp.Rows.Add(mTable.TableID,mTable.Capacity);
}
catch(SqlException ee)
{
if (ee.Number == 2627)
{
MessageBox.Show("Sorry, This Table Is Already Reserved!");
if (Con.State == ConnectionState.Open) { Con.Close(); }
return;
}
MessageBox.Show("Exception: " + ee.Message);
}
谁能告诉我如何处理这个异常?
Can anyone please tell me how to handle this exception?
推荐答案
由于您在本地 DataTable
中定义了约束,因此您正试图捕获错误类型的异常.而不是 SqlException
,一个 ConstraintException
被抛出.
Since you have define your constraint in the local DataTable
, you're trying to catch the wrong type of exception. Instead of SqlException
, a ConstraintException
is thrown.
立即解决方法是更改 try
子句中的异常类型:
An immediate fix would be, to change the type of exception in your try
clause:
try
{
dtemp.Rows.Add(mTable.TableID,mTable.Capacity);
}
catch (ConstraintException ee)
{
// handle the exception here
}
如果您想在数据库中检查您的约束,那么这就是您想要定义它的地方,而不是在DataTable
中.在这种情况下,SqlException
将被抛出,但仅当您将数据发送到数据库时,而不是在您向 DataTable
添加一行时.
If you want to check your constraint in the database, then that's where you want to define it instead of in the DataTable
. In this case, SqlException
will get thrown, but only when you send the data to the database, not when you add a row to the DataTable
.
这篇关于如何在C#中添加记录时处理数据表中的唯一约束异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!