記錄通過收費站車輛資訊:時間、車型、金額、車輛影像等,涉及大量多媒體資料處理。以 Delphi 流資料類型(TStream)為核心橋梁說明實作。
桌面型資料庫存取少量多媒體尚可,資料量增大後效能急劇下降,甚至假死。作者曾用 Visual FoxPro 管理 1 萬筆學生照片,查詢極慢被迫放棄。
採用企業級資料庫:SQL Server、Sybase、Oracle 具強大效能、完善管理、可靠安全、優異網路功能、豐富資料型別(如 Image 存 0~2GB 二進位資料)及針對多媒體優化引擎。綜合考量選 SQL Server 2000 標準版。
SQL Server Image 欄位無法直接寫入,需中介步驟。TStream 以串流形式儲存字元/非字元資料,如記憶體中可變大小緩衝區,適合作橋梁。
SaveToImage 函數:將 TStream 存入 Image 欄位。
function SaveToImage(const Stream: TStream; const AField: TField): Boolean;
var FieldStr: string; PFieldStr: PChar;
begin
Result := False;
if Assigned(AField) and Assigned(Stream) then begin
try
Stream.Seek(0, 0);
SetLength(FieldStr, Stream.Size);
PFieldStr := PChar(FieldStr);
Stream.Read(PFieldStr^, Stream.Size);
AField.Value := FieldStr;
Result := True;
except end;
end;
end;
呼叫範例:
var FS: TFileStream;
begin
FS := TFileStream.Create('C:\Car001.jpg', fmOpenRead);
SaveToImage(FS, AdoDataSet1.FieldByName('st_img'));
FS.Free;
end;
利用 SQL Server BCP 工具大量複製資料(含二進位)。
資料庫 → 外部檔案:
var S1: string;
begin
S1 := 'bcp "select * from st2002..st2002_sf where st_flag=1" queryout c:\Media_data.dat -N -P -S sunnynt\hy2002';
WinExec(PChar(S1), SW_SHOW);
end;
queryout:查詢結果輸出至檔案。-N:大量複製模式(保留原生資料型別)。-P:預設密碼,-S:伺服器/執行個體。外部檔案 → 資料庫:
var S1: string;
begin
S1 := 'bcp ST2002..ST2002_SF in c:\Media_data.dat -n -E -P -S sunnynt\hy2002';
WinExec(PChar(S1), SW_SHOW);
end;
in:從檔案匯入資料表。-n:原生模式,-E:保留識別欄位值。與存儲逆向操作,同樣透過 TStream 橋梁。
LoadFromImage 函數:將 Image 欄位讀入 TStream。
function LoadFromImage(const AField: TField; const Stream: TStream): Boolean;
var ResultStr: string; PResultStr: PChar;
begin
Result := False;
if Assigned(AField) and Assigned(Stream) then begin
try
ResultStr := AField.Value;
PResultStr := PChar(ResultStr);
Stream.Write(PResultStr^, Length(ResultStr));
Stream.Seek(0, 0);
Result := True;
except end;
end;
end;
呼叫並顯示影像:
var FS: TFileStream;
begin
FS := TFileStream.Create('c:\Car001.jpg', fmCreate);
LoadFromImage(AdoDataSet1.FieldByName('st_img'), FS);
FS.Free;
Image1.Picture.LoadFromFile('c:\Car001.jpg');
end;