数据库

位置:IT落伍者 >> 数据库 >> 浏览文章

DELPHI存取JPEG文件到SQL Server数据库


发布日期:2020年08月19日
 
DELPHI存取JPEG文件到SQL Server数据库
近日笔者书写一个小型的学生管理系统时需要用到ADO控件存取SQL Server数据库图片查看资料发现基本都是针对BMP文件进行操作(巨增数据库大小)但发现了eagletian高手翻译的ADO英文技术文档里面涉及到了数据库存取JPEG文件的关键技术在win+sql server桌面版中测试通过运行良好现于源码公开如下

unit Unit;

interface

uses

Windows Messages SysUtils Classes Graphics Controls Forms Dialogs

ExtCtrls DBCtrls Grids DBGrids Db ADODBjpeg StdCtrlsdbtables;

{一定要USES JPEG单元使能存储JPG文件格式}

type

TForm = class(TForm)

DataSource: TDataSource;

ADOQuery: TADOQuery;

DBGrid: TDBGrid;

DBNavigator: TDBNavigator;

Image: TImage;

savebutton: TButton;

showbutton: TButton;

OpenDialog: TOpenDialog;

ADOQueryid: TIntegerField;

ADOQuerypic: TBlobField;

procedure savebuttonClick(Sender: TObject);

procedure showbuttonClick(Sender: TObject);

procedure DBNavigatorClick(Sender: TObject; Button: TNavigateBtn);

private

{ Private declarations }

public

{ Public declarations }

end;

var

Form: TForm;

implementation

{$R *DFM}

function JpegStartsInBlob(PicField:TBlobField):integer;

var

ghy: TADOBlobstream;

buffer:Word;

hx: string;

begin

Result := ;

ghy := TADOBlobstreamCreate(PicField bmRead);

try

while (Result = ) and (ghyPosition + < ghySize) do

begin

ghyReadBuffer(buffer );

hx:=IntToHex(buffer );

if hx = FF then begin

ghyReadBuffer(buffer );

hx:=IntToHex(buffer );

if hx = D then Result := ghyPosition

else if hx = FF then

ghyPosition := ghyPosition;

end; //if

end; //while

finally

ghyFree

end; //try

end;

procedure TFormsavebuttonClick(Sender: TObject);

var

picstream:tadoblobstream;

begin

adoqueryedit;

picstream:=tadoblobstreamCreate(tblobfield(adoqueryfields[])bmWrite);

if formopendialogexecute then

begin

picstreamLoadFromFile(opendialogfilename);

picstreamPosition:=;

adoqueryedit;

tblobfield(adoqueryFields[])loadfromstream(picstream);

adoquerypost;

end;

end;

procedure TFormshowbuttonClick(Sender: TObject);

var

ghy:TADOBlobstream;

pic:tjpegimage;

begin

ghy := TADOBlobstreamCreate(Adoquerypic bmRead);

try

ghySeek(JpegStartsInBlob(Adoquerypic)soFromBeginning);

Pic:=TJpegImageCreate;

try

PicLoadFromStream(ghy);

ImagePictureGraphic:=Pic;

finally

PicFree;

end;

finally

ghyFree

end;

end;

procedure TFormDBNavigatorClick(Sender: TObject; Button: TNavigateBtn);

begin

if button in [nbFirst nbPrior nbNext nbLast] then showbuttonClick;

end;

end

如果数据库中要存储的是BMP文件则在procedure TFormshowbuttonClick(Sender: TObject);过程中代码更改如下即可存储显示BMP文件格式的操作

procedure TFormshowbuttonClick(Sender: TObject);

var

ghy:TADOBlobstream;

pic:tbitmap;

begin

ghy := TADOBlobstreamCreate(Adoquerypic bmRead);

try

{ ghySeek(JpegStartsInBlob(Adoquerypic)soFromBeginning);}

Pic:=TbitmapCreate;

try

PicLoadFromStream(ghy);

ImagePictureGraphic:=Pic;

finally

PicFree;

end;

finally

ghyFree

end;

end;

到此用DELPHI存取JPEG文件到SQL Server数据库中的具体操作已经叙述完毕

               

上一篇:Delphi开发经验技巧:使用SQL语句保存数据

下一篇:Excel数据保存数据库与ConnectionString