Google
 

Kamis, 17 Januari 2008

BLOB Field using ZeosDBO 6.6.x

Hi, I want to share how to save and load BLOB from database. The database I use here is Firebird, but I think Zeos behaviour is same. This example below is to save and load the JPEG image into and from Firebird database. If you use bitmap image then you can display it using TDBImage, but for JPEG you cann't do that otherwise you get an error that said that it is not a valid bitmap. So in this code, for display the image from database I use TDBImage with no binding (the datasource property still null). So let's look the code:

The component that I dropped:

uses jpeg, ........
type
TForm1 = class(TForm)
con1: TZConnection;
qr1: TZQuery;
qr1aaa: TStringField; //persistant field that only string value
qr1gambar: TBlobField; //persistent field "gambar" that used to save JPEG image
ds1: TDataSource;
dlgOpen1: TOpenDialog;
dbnvgr1: TDBNavigator;
dbeaaa: TDBEdit; //use binding to connect to field "aaa"
btn1: TButton;
btn2: TButton;
dbimg1: TDBImage;
procedure btn1Click(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btn2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

The code:

procedure TForm1.FormShow(Sender: TObject);
begin
//Connect to Database and open query
con1.Connect;
qr1.Close;
qr1.Open;
end;

procedure TForm1.FormClose(Sender: TObject; var Action: TCloseAction);
begin
//Close query and connection
qr1.Close;
con1.Disconnect;
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
if dlgOpen1.Execute then
begin
//Load JPEG image (or anything type of file) into database
qr1gambar.LoadFromFile(dlgOpen1.FileName);
end;
end;

procedure TForm1.btn2Click(Sender: TObject);
var j:TJPEGImage;
begin
//Display image from database to TDBimage (dbimg1) component
j:=TJPEGImage.Create;
j.Assign(qr1gambar);
dbimg1.Picture.Assign(j);
FreeAndNil(j);
end;


How the code work?
"btn1Click" method is clicked after the dataset is in edit or insert mode, then after it load from file then post it (I use DBNavigator in the above example). And then "btn2Click" is for display image from database to TDBImage component. Simply enough? yes, that's all.

Now, what about other format like Word, Excel or PDF document that you want to extract from the database? (the save method is same). The answer is, save it to file again. Zeos already implement it well, so you can do like this:

qr1gambar.SaveToFile('c:\somefile.doc');

Also simply enough? yes. So don't worry to use BLOB field with Zeos component :)
How about to save/load it from Stream? You can also use "SaveToStream" and "LoadFromStream" method.

Tidak ada komentar: