也来谈谈数据库中的图象存取

王朝delphi·作者佚名  2006-01-08
窄屏简体版  字體: |||超大  

关于数据库中的图象存取,网上的资料多是直接用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

E_mail: zhangyi1980912@sina.com QQ: 8133413 张家恶少

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有 導航