我在BDE所有數據庫使用EDatabaseErrorBDE VS ADO數據庫中的錯誤處理
try
//all database related operations
Except
on EDatabaseError do
begin
showmessage(e.message)
end;
End;
但ADO我有關的相關誤差修改可以處理工作的Delphi 7 +的SQLserver
嘗試不同的例子,我得到不同的錯誤,如EOleError/EDatabaseError/...
我嘗試了2點以下在ADO中引發錯誤,並且我得到了不同的錯誤
1)在sql server存儲過程中,我在第一行發生錯誤。當我執行該程序使用在德爾福TADOStoredProc我得到EOleError。
2)在TADOQuery我已經寫了錯誤的SQL語句,所以當我打開 TADOQUery我得到EDatabaseError。
所以現在我很困惑如何處理ADO錯誤。 我不想檢查所有的錯誤(EOleError,EDatabaseError,EAdoError ...)在每一個形式,所以我寫了2個例子, 請建議我哪一個是好的。如果兩者都不對,請給我一個很好的例子。
實施例1:
我在這裏僅示出一個示例形式中的Delphi所以程序HandleErrors和功能GetErrorDescription可能看起來笨。我不想在所有表格中編寫相同的 代碼。當涉及到真正的場景我要保留德爾福程序處理錯誤和函數GetErrorDescription在不同的單位,並在整個應用程序中使用該單位。
type
TForm1 = class(TForm)
ADOConnection1: TADOConnection;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
Procedure HandleErrors(e: Exception);
function GetErrorDescription : WideString;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
function TForm1.GetErrorDescription : WideString;
var
LastErrorIndex : Integer;
begin
LastErrorIndex :=ADOConnection1.Errors.Count-1;
Result:=ADOConnection1.Errors.Item[LastErrorIndex].Description;
//Code :=ADOConnection1.Errors.Item[LastErrorIndex].NativeError;
end;
procedure TForm1.HandleErrors(e: Exception);
var
Code: Integer;
ErrorDescription: WideString ;
begin
if e is EOleError then
ShowMessage(GetErrorDescription)
else
if e is EDatabaseError then
ShowMessage(GetErrorDescription)
else
if e is EADOError then
ShowMessage(GetErrorDescription)
else
ShowMessage(GetErrorDescription)
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
try
// any database related operations
except
on E : Exception do
begin
HandleErrors(E);
end;
end;
end;
end.
實施例2:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,ADODB, StdCtrls, DB,COMOBJ;
type
TForm1 = class(TForm)
ADOConnection1: TADOConnection;
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
var
LastErrorIndex : Integer;
begin
try
// any database related operations
except
on E : Exception do
begin
LastErrorIndex :=ADOConnection1.Errors.Count-1;
ShowMessage(ADOConnection1.Errors.Item[LastErrorIndex].Description);
end;
end;
end;
end.
其實例是更好的。你可以請建議一個好的
「我不想來檢查每一個表單中的所有錯誤」嗯,這就是你將不得不如果你堅持把AdoConnections和數據集在窗體上做什麼。這不是他們的地方(除了在v小試驗檯上)。將它們集中(集中)在DataModule中,習慣從表單中訪問它們。順便說一句,我昨天給你的q的答案告訴你如何實現一個集中的異常處理程序(請參閱代碼中對Application.OnException的引用)。 – MartynA
@MartynA:(+ 1)我正在研究一箇舊的應用程序,它在表單上有很多很多的數據集,我現在不想將所有這些東西移動到數據模塊。所以我正在檢查如何處理異常。我將檢查Application.OnException。非常感謝你。 – DelphiLearner
@MartynA:可以使用示例2嗎? – DelphiLearner