Reputation: 23295
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
?
Upvotes: 2
Views: 7092
Reputation: 103
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
Upvotes: 2
Reputation: 1
try {
cmd.ExecuteNonQuery();
} catch (OleDbException ex) {
if (ex.ErrorCode == -2147467259) {
MessageBox.Show("Hi , yes");
}
}
Upvotes: -1
Reputation: 23295
The JET error code for a OleDbException
can be found from:
OleDbError.SQLState
which is 3022
for the exception provided in the question.
Upvotes: 2
Reputation: 124804
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.
Upvotes: 7