数据库中的图象存取

来源:互联网 发布:鞋子进销存软件 编辑:程序博客网 时间:2024/05/17 07:28
关于数据库中的图象存取,网上的资料多是直接用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
 
原创粉丝点击