2009年5月29日

Delphi OLEDB 使用 ErrorCode 做錯誤處理

在 Form 上放一個 TMemo,一個 TADOConnection 及一個 TADODataSet

uses
ComObj, OleDB;

在元件屬性 ADOConnection1.ConnectionString 中指定資料庫,例如 DBDEMOS.udl
在元件屬性 ADODataSet1.Connection 指定為 ADOConnection1
在元件屬性 ADODataSet1.CommandText 寫入一個不存在的 QUERY TABLE,例如
select * from x

在 FormCreate 事件中加入

procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Clear;
try
ADODataSet1.Active := True;
except
on E: EOleException do begin
Memo1.Lines.Add('ErrorCode: ' + IntToHex(E.ErrorCode, 8));
Memo1.Lines.Add(E.Message);
case E.ErrorCode of
DB_E_NOTABLE: begin
// The specified table does not exist
Memo1.Lines.Add('Table 不存在');
end;
DB_E_INTEGRITYVIOLATION: begin
// A specified value violated the integrity constraints
// for a column or table
Memo1.Lines.Add('違反完整性約束,可能為資料重複');
Memo1.Lines.Add('或沒有外鍵所參考的值存在');
end;
DB_E_ERRORSINCOMMAND: begin
// The command contained one or more errors
Memo1.Lines.Add('SQL Command 發生一或多個錯誤');
end;
// 可加入其它的 ErrorCode 來做處理
else ;
end;
end;
end;
end;

{ Memo
ErrorCode: 80040E37
Microsoft Jet 資料庫引擎無法找到輸入資料表或查詢 'x'。請確定它是存在的而且名稱沒有拼錯。
Table 不存在
}

沒有留言:

網誌存檔