0

I have an app that uses OleDB to connect to an Access database. I am trying to create some error handling for inserting duplicate records, where there is a unique index.

When this error is thrown I get the error code -2147467259 on the exception. However other errors also give the same error code; Database full, or column missing for example.

Is there a way to determine between these different errors without using the error message itself which every part of me says will be unreliable.

I have looked at .innerexception, in the case of inserting duplicates there is no inner exception.

I have also looked at .SQLState property, it appears that this is an old method not really within use in the 4.0 framework. I could apply this but I would likely be using on error, rather than my desired try catch.

My code at the moment:

            Try
                Sender.cmdOLEDB.ExecuteNonQuery()
            Catch ex As OleDbException

            End Try
4

1 回答 1

0

冒着成为那个坚持认为您的根本问题是这里真正问题的人的风险......数据库是这里的真正问题。

我假设你有某种自然密钥(否则你不会得到重复的密钥异常)而不是生成的密钥。我建议更改表格,这样您就不必担心尝试找出由于 PK 错误而导致插入失败的原因。

我见过类似于这种逻辑的东西,其中一位同事将保存方法实现为:

try
{
    insertCommand.ExecuteNonQuery();
}
catch(Exception ex)
{
    updateCommand.ExecuteNonQuery();
}

这……不好。

于 2013-07-16T14:31:06.897 回答