陷阱密钥违规

Ale*_*ith 3 delphi ado delphi-7

嗨,我正在尝试做一些异常处理并拦截重复的字段值(密钥违规)错误.从我寻找解决方案我已经看到很多建议来捕获所有错误使用

try
(enter code)
except on E: EDatabaseError do
showmessage (Error message);
end; 
Run Code Online (Sandbox Code Playgroud)

但我想特别回应一个密钥违规,它使用ADO访问表.

Ken*_*ite 7

如果您想要处理的唯一错误是具有"重复值"消息的错误,这将有效:

try
  // Your code
except
  on E: EOleException do
  begin
    // The better way is to find out what E.ErrorCode is
    // for this specific exception, and handle it instead
    // of checking the string - you didn't provide the
    // ErrorCode, though.
    // If E.ErrorCode = <whatever> then
    //
    if Pos('duplicate value', E.Message) > 0 then
      // You've got a duplicate with the message above
      // Do whatever handles it
    else
      raise;
  end;
  // If you want to handle other exception types (eg., EDataBaseError),
  // you can do so here:
  //  on E: EDataBaseError do
  //    HandleDBError;
end;
Run Code Online (Sandbox Code Playgroud)

  • @ user1277240,只是导致异常发生,并在异常代码中执行`ShowMessage(Format('ErrorCode:%d',] E.ErrorCode]));`来获取ErrorCode; 它将永远是相同的,如果语言改变,消息可以改变(正如大卫指出的那样). (2认同)
  • @David,感谢你抓住了我在上一次修订中错过的'else raise`.我以为我已经添加了它,只是注意到我没有,当我进去编辑它时就在那里.以为我疯了,直到我回去并刷新问题页面并看到你的编辑.:) (2认同)

RRU*_*RUZ 6

EDatabaseError只是没有有关该错误的附加信息的通用excption类,以获取有关ADO一个错误的扩展信息,你必须使用TADOConnection.Errors属性时获得specifc错误代码Key violation引发异常,该检查NumberNativeError性能.

您可以在此处找到有关此主题的更多文档