關於數據庫中的圖象存取,網上的資料多是直接用Table或者Query 等控件然後利用流作為媒介來完成。目前我還沒看到封裝在一個類裡面,完全用SQL語句來實現圖象的
存取。前段時間開發一個運證管理系統就碰到了這樣一個問題:要把每個司機的照片
入庫。我們可以在主界面放置一個TImage和OpenDialog對話框進行照片的選擇,可是
最後怎樣將照片存入數據庫呢?
下面提供源代碼讓大家分析(其中刪去了一些不相關的東西):
THuman=class (TComponent)
Private
Name:string;
IDCard:string;
Sex:Byte;
Photo:TImage;
FQuery:TQuery;
FDatabase:TDatabase;
- - -
publisned
property Name:string read FName write FName;
property IDCard:string read FIDCard write FIDCard;
property Sex:Byte read FSex write FSex;
property Photo:TImage read FPhoto write FPhoto;
property Query:TQuery read FQuery write FQuery;
property Database:TDatabase read FDatabase write FDatabase;
function THuman.Insert: Boolean;
var
Sqlstr:string;
lStream:TMemoryStream;
lPicture:TJPEGImage;
begin
lStream:=TMemoryStream.Create;
lPicture:=TJPEGImage.Create;
// FPhoto為TImage變量,在主界面可以選擇一張照片
if FPhoto.Picture.Graphic<>nil then
begin
lPicture.Assign(FPhoto.Picture.Graphic);
lPicture.SaveToStream(lStream);
end;
if FDatabase.InTransaction then FDatabase.Commit;
FDatabase.StartTransaction;
Query.Sql.text:= 'Insert Into Human(Name,IDCard,Sex,Photo) values(:Name,:IDCard,:Sex,:Photo)’;
子段前加冒號,動態生成SQL參數,然後給參數賦值:
Query.ParamByName('Name').asstring:=’張家惡少’;
Query.ParamByName('IDCard').asstring:=Something;
Query.ParamByName('Sex').asstring:=Something;
Query.ParamByName('Photo').LoadFromStream(lStream,ftBlob);
try
Query.Prepare;
Query.execSQL;
Query.Close;
FreeAndNil(lStream);
FreeAndNil(lPicture);
Result:=True;
FDatabase.Commit;
except
FDatabase.Rollback;
Query.Close;
FreeAndNil(lStream);
FreeAndNil(lPicture);
Result:=False;
end;
最後要主要釋放動態生成的LStream 和 LPicture