Delphi中的TADODataset catch Post方法错误代码
我有一个数据集,我用它来捕捉错误:Delphi中的TADODataset catch Post方法错误代码,delphi,Delphi,我有一个数据集,我用它来捕捉错误: try FDataSource.DataSet.Post; ShowMessage('success message!'); except on E : EDatabaseError do begin if (Pos('duplicate value', E.Message) > 0) or (Pos('duplicate key', E.Message) > 0) then ShowMessage('m
try
FDataSource.DataSet.Post;
ShowMessage('success message!');
except
on E : EDatabaseError do
begin
if (Pos('duplicate value', E.Message) > 0) or (Pos('duplicate key', E.Message) > 0) then
ShowMessage('my custom error message')
else
ShowMessage('generic db error message');
end;
end;
这是一个可怕的解决方案,因为它依赖于在错误消息中查找字符串“duplicate value”或“duplicate key”
我希望能够得到一些错误代码
有什么方法可以得到它吗?您可以通过AdoConnection对象捕获错误
TAdoConnection
有一个Errors
对象(请参见AdoInt.Pas中的定义)。到
调查一下,我在服务器上使用了一个存储过程,定义为
create PROCEDURE [dbo].[spRaiseError](@AnError int)
AS
BEGIN
declare @Msg Char(20)
if @AnError > 0
begin
Select @Msg = 'MyError ' + convert(Char(8), @AnError)
RaisError(@Msg, 16, -1)
end
else
select 1
END
然后,在我的Delphi代码中,我有如下内容:
uses [...] AdoInt, AdoDB, [...]
procedure TForm1.Button1Click(Sender: TObject);
var
S : String;
IErrors : Errors;
IError : Error;
ErrorCount : Integer;
i : Integer;
begin
S := 'exec spRaiseError ' + Edit1.Text;
AdoQuery1.SQL.Text := S;
try
AdoQuery1.Open;
except
IErrors := AdoConnection1.Errors;
ErrorCount := IErrors.Count;
for i := 0 to ErrorCount - 1 do begin
IError := IErrors.Item[i];
S := Format('error: %d, source: %s description: %s', [i, IError.Source, IError.Description]);
Memo1.Lines.Add(S);
end;
Caption := IntToStr(ErrorCount);
end;
end;
如果我将AdoQuery1的Sql.Text设置为“从我得到的任何内容中选择*”
错误:0,源:用于SQL Server的Microsoft OLE DB提供程序描述:无效的对象名称“anything”
如果您尝试它,您会发现Errors
集合的内容
是累积的,但是错误
有一个清除
方法来清除它
看
有关更多信息(链接由Remy Lebeau提供)该对象具有错误代码和属性。更多细节。例如,定义可能的
Number
值?若否,原因为何?