2

I need to catch the following specific exception:

System.Data.OleDb.OleDbException was caught ErrorCode=-2147467259
Message="The changes you requested to the table were not successful because they would create duplicate values in the index, primary key, or relationship. Change the data in the field or fields that contain duplicate data, remove the index, or redefine the index to permit duplicate entries and try again." Source="Microsoft JET Database Engine" StackTrace: at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr) at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult) at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method) at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()

I'm not sure what ErrorCode is but it looks unreliable.

Can I rely on Message being identical across platforms?

Can I somehow use the OleDbHResult hr value found in the stack trace? (See https://stackoverflow.com/a/991660/327528)

Is the only solution to do a text search of Message for words like duplicate and primary key?

4 Answers 4

7

You're right that the ErrorCode (-2147467259 = 0x80004005 = E_FAIL) is too generic, and relying on the message is very fragile - e.g. consider localization.

I would look at the OleDbException.Errors collection to try to find something more specific.

2
  • What about OleDbHResult hr ?
    – CJ7
    Oct 9, 2012 at 9:43
  • @CJ7 - if you look at System.Data.dll with Reflector, you'll see the definition of the internal enum OleDbhResult. From what I can see it's the same as ErrorCode = E_FAIL, i.e. non-specific.
    – Joe
    Oct 9, 2012 at 9:47
2

The JET error code for a OleDbException can be found from:

OleDbError.SQLState

which is 3022 for the exception provided in the question.

2

You can try using the SQLState property for each error in the OleDbException.Errors collection

Found this reference: SQL State Error Codes <- Not working anymore
Updated reference: SQL error codes

1
-1
try {
  cmd.ExecuteNonQuery();
} catch (OleDbException ex) {
  if (ex.ErrorCode == -2147467259) {
    MessageBox.Show("Hi , yes");
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.