Ads

Ads

Translate

Showing posts with label Tanya Jawab Delphi. Show all posts
Showing posts with label Tanya Jawab Delphi. Show all posts

Thursday, 14 November 2013

Delphi Knowledge Base v1.5

Delphi Knowledge Base is a unique collection of Delphi tips and articles where Delphi programmers can find ideas, solutions and share their experience. Everyone of us occasionally experience what it is when you can not find the right way of solving the problem and how much time it takes. But have you ever thought that maybe thousands of people already had this kind of problem and solved it successfully? So the main idea of this program is that you can find the article you need and also share your articles with other users via the Internet. This exchange helps to expand the program and to enrich it with new articles every day. The program enables user to browse articles that are already existing in a data base and to add new ones. Articles are formatted so that they could be copied and pasted right into your program.

Friday, 12 April 2013

Handling Images in MySQL

We will be using ZEOS library to provide access to our MySQL server. If you don't have it, get ithere (Zeos at sourceforge). Zeos is an open source project which aiming to provide Delphi users a single library, thus a single framework, to access many kind of database.

Before creating our demo project. We have to create our sample database. Using any MySQL client you prefer (e.g. mysql command line or PhpMyAdmin), create a new database in your mysql server. Name the database Movies. In the database, create new table (name it Movies) with this structure:
CREATE TABLE IF NOT EXISTS `Movies` (
`ID` int(11) NOT NULL AUTO_INCREMENT
, `Title` varchar(255) NOT NULL
, `ImdbUrl` varchar(255) DEFAULT NULL
, `Picture` blob
, PRIMARY KEY (`ID`)
, KEY `Title` (`Title`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

Let's use our demo project with MS Access for the start of mySQL demo project. Open the MS Access demo project, then:
  • rename the project into StoreImageDemo_MySQL_Zeos
  • rename the main form unit into frmStoreImageDemo_MySql_Zeos
  • while keeping the component names, replace ADO components with respected counterparts in ZEOS, i.e.
  • replace TADOConnection with TZConnection (keep the cnnMain name)
  • replace TADOTable with TZTable (keep tblMovies name)
  • replace TADOCommand with TZQuery (keep qCmd name)
Then you will get the layout of the main form into something like this:


For the new cnnMain:
  • Set Protocol property into mysql-5
  • Set Host property into your mySQL server host address (e.g. localhost, 127.0.0.1).
  • Set User and Password properties with proper credentials to login to your mySql server.
  • If your mySql server use custom port, update Port property with correct port number, otherwise leave it as is.
  • Set Connected property to True.
Wire tblMovies's and qCmd's Connection properties to cnnMain. Set dsMovies' Dataset totblMovies.

Set Movies to tblMovies' TableName property. Build the persistent fields for tblMovies by double clicking it and then Add all fields in the dialog that pops up.

Give the following SQL command to qCmd's CommandText.
UPDATE Movies SET Picture=:Picture WHERE ID=:ID
Check that qCmd has two parameters, Picture and ID, by opening its Params property in object inspector.

Writing Image With Table-kind of Dataset

Note that we don't have to change anything here. Code that works with TADOTable also works withTZTable. This is caused by both still use the same framework. So there is nothing we need to change here. See the explanation for MS Access.

Writing Image with SQL command
Here also everything is nearly the same with when we are working with MS Access database. The only differences are that TZQuery uses the name of Params for its property that containing parameters, while TADOCommand uses the name of Parameters. And TZQuery uses the nameExecSQL for executing data manipulation sql command instead of Execute in TADOCommand.

So basically we ended with the same code for btnAddPictSQL onclick event handler, we only need to change "Parameters" into "Params", and "Execute" into "ExecSQL". Like this:

procedure TForm1.btnAddPictSQLClick(Sender: TObject);
var
vFileStream: TStream;
begin
// do we have record to store the picture to? Don't continue if not
if tblMovies.IsEmpty then Exit;
// do the user select a picture file? Dont continue if not
if not OpenPictureDialog1.Execute then Exit;
// load the picture file into a stream
vFileStream := TFileStream.Create(OpenPictureDialog1.FileName, fmOpenRead or fmShareDenyNone);
try
// give ID of the current movie record to the :ID parameter of qCmd
qCmd.[B]Params[/B].ParamByName('ID').Value := tblMoviesID.Value;
// Assign the content of FS stream to the :Picture parameter
qCmd.[B]Params[/B].ParamByName('Picture').LoadFromStream(vFileStream, ftBlob);
// execute the sql
qCmd.[B]ExecSQL[/B];

// refresh the table so it shows the new picture
RefreshTable;
finally
vFileStream.Free;
end;
end;

Reading Image from Dataset
Here it's also the same. Since at this level both (zeos and ado) still using the same framework. Therefore we can keep the code that we previously use to read image from MS Access.

Isn't it cool? We hardly write new codes when we are migrating from MS Access to mySQL.


Download : http://www.facebook.com/download/242147332595934/Demo_MySql_Zeos.zip
Oleh : Luthfi Hakim

Storing Images in Database Ms.Access

Overview
Beside plain simple data, such as strings and numbers, in most (if not all) modern database we usually can also store digital values of nearly unlimited size. We can use this for example to store images, text files, executables, and binary libraries. This kind of values usually called BLOB, short for binary large object. Fields to store these values also refered as blob fields.

See this wikipedia page for more information about BLOB.

The following database is known to support blob fields (note: the list covers only a very small fraction of database supporting blob fields).
  • MySQL
  • MS SQL Server
  • MS Access
  • Interbase
  • Firebird

Handling BLOB value in Delphi datasets
There is no primitive data type in Delphi directly available to handle BLOB value. Therefore we have to settle with handling BLOB as stream. TBlobStream is a descendant of TStream that was defined to handle BLOB values as stream. See here for official information on TBlobStream.

Excerpt from Delphi documentation about TBlobStream:
Quote
DBTables.TBlobStream is a stream object that provides services which allow applications to read from or write to field objects that represent Binary large object (BLOB) fields.

Use DBTables.TBlobStream to access or modify the value of a BLOB field in a BDE-enabled dataset. TBlob stream works with persistent TBlobField objects (including descendants of TBlobField such as TGraphicField and TMemoField). BLOB fields use BLOB streams to read data from and write data to the dataset.

DBTables.TBlobStream allows objects that have no specialized knowledge of how data is stored in a BLOB field to read or write such data by employing the uniform stream mechanism.

To use a BLOB stream, create an instance of DBTables.TBlobStream, use the methods of the stream to read or write the data, and then free the BLOB stream. Do not use the same instance of DBTables.TBlobStream to access data from more than one record. Instead, create a new DBTables.TBlobStream object every time you need to read or write BLOB data on a new record.

The most important thing you should note is that you can not reuse an instance of TBlobStream. You must free it as soon as you are done with it, and create new one for another record.

Another important thing you should remember is that it is prefered to call a dataset'sCreateBlobStream method instead of directly call TBlobStream's constructor. Because this approach will give the dataset a chance to prepare itself.

Writing BLOB field
Basic steps in writing to a BLOB field:
  • If the dataset is no in editing mode, put the dataset into the mode by either calling Edit orInsert.
  • Create a TBlobStream by calling respected dataset's CreateBlobStream method and specifying the field and bmWrite as access mode.
  • Fill the returned TBlobStream with your binary value.
  • Free the TBlobStream.
  • Store the changes by posting the modification, either by calling Post or CheckBrowseMode.

Reading BLOB field
Basic steps in writing to a BLOB field:
  • Create a TBlobStream by calling respected dataset's CreateBlobStream method and specifying the field and bmRead as access mode.
  • Read the content of the returned TBlobStream
  • Free the TBlobStream.
  • Use the read content according to task in hand

In next sections I show you the implementations of the above steps in order to store and read images to and from some database.

Handling Images in MS Access
For our demo project with MS Access, create a new Delphi application project. Drop these components to the main forms and rename them respectively:
  • TADOConnection, cnnMain
  • TADOTable, tblMovies
  • TDataSource, dsMovies
  • TOpenPictureDialog, OpenPictureDialog1
  • TADOCommand, qCmd
  • TDBGrid, DBGrid1
  • TImage, Image1
  • TBitBtn, btnOpenUrl
  • TBitBtn, btnAddPict
  • TBitBtn, btnAddPictSQL

Arrange the controls/components into a layout something like this:

fmMain_Access_design001.png

Wire tblMovies's and qCmd's Connection properties to cnnMain. Set dsMovies' Dataset totblMovies. Wire DBGrid1's DataSource to dsMovies. Build the connection string of cnnMain by double clicking it. Make sure the connection string pointing to the sample ms access datase attached here (download and save it somewhere in your computer).

Set Movies to tblMovies' TableName property. Build the persistent fields for tblMovies by double clicking it and then Add all fields in the dialog that pops up.

Give the following SQL command to qCmd's CommandText.
UPDATE Movies SET Picture=:Picture WHERE [ID]=:ID
Check that qCmd has two parameters, Picture and ID, by opening its Parameters property in object inspector.

Writing Image With Table-kind of Dataset
What I mean with Table-kind datasets are datasets that containing records, e.g. TTable,TADOTable, TQuery with SELECT query, and TADODataset with SELECT query. For these kind of datasets, we can store BLOBs directly to the corresponding fields. This is where TBlobStream plays important role.

In our demo project we will use a TADOTable which we named tblMovies.

Put the following codes for btnAddPict's event handler:
procedure TForm1.btnAddPictClick(Sender: TObject);
var
  vBlobStream: TStream;
  vFileStream: TStream;
  vEditing: Boolean;
begin
  // do we have record to store the picture to? Don't continue if not
  if tblMovies.IsEmpty then Exit;
  // do the user select a picture file? Dont continue if not
  if not OpenPictureDialog1.Execute then Exit;
  // are we in editing mode? Enter into one if not
  vEditing := tblMovies.State in [dsEdit, dsInsert];
  if not vEditing then tblMovies.Edit; // enter editing mode if not in one
  try
    // create writable TBlobStream for field 'Picture' of tblMovies
    [b]vBlobStream := tblMovies.CreateBlobStream(tblMoviesPicture, bmWrite);[/b]
    try
      // create stream of the selected picture file
      vFileStream := TFileStream.Create(OpenPictureDialog1.FileName, fmOpenRead or fmShareDenyNone);
      try
        // copy the content of picture stream to the TBlobStream
        [b]vBlobStream.CopyFrom(vFileStream, 0);[/b]
      finally
        vFileStream.Free;
      end;
    finally
      // freeing writable TBlobStream also writes its content to the underlying field
      vBlobStream.Free;
    end;
  finally
    // post the changes if we are the one putting into editing mode
    if not vEditing then tblMovies.CheckBrowseMode;
  end;
end;

I think the code and the comments pretty much explained everything about the process.

Writing Image with SQL command
In this case we want to store images using SQL command INSERT or UPDATE. It will be different with the method we used with table-kind of datasets, since obviously here we don't have a TField to help us out. No TBlobStream for us here. However we have TParameter objects to work with.

Basically TParameter is a way to communicate with our sql command. We pass values usingTParameter, and we also read values using TParameter. Declaration of TParameter is done directly inside the sql command itself. Just add a colon (:) in front of the parameter's name, and later Delphi will create instance(s) of corresponding TParameter(s) for you.

For our example here, we have given this sql: UPDATE Movies SET Picture=:Picture WHERE [ID]=:ID. The bold parts are the ones 
that define our two TParameter-s, i.e. Picture and ID. Of course initially these TParameter-s have no value. So before we execute the sql, we need to give values to them. TParameter is capable to hold BLOB value, like I show you in the OnClick event handler of btnAddPictSQL below:

procedure TForm1.btnAddPictSQLClick(Sender: TObject);
var
  vFileStream: TStream;
begin
  // do we have record to store the picture to? Don't continue if not
  if tblMovies.IsEmpty then Exit;
  // do the user select a picture file? Dont continue if not
  if not OpenPictureDialog1.Execute then Exit;
  // load the picture file into a stream
  vFileStream := TFileStream.Create(OpenPictureDialog1.FileName, fmOpenRead or fmShareDenyNone);
  try
    // give ID of the current movie record to the :ID parameter of qCmd
    qCmd.Parameters.ParamByName('ID').Value := tblMoviesID.Value;
    // Assign the content of FS stream to the :Picture parameter
    [b]qCmd.Parameters.ParamByName('Picture').LoadFromStream(vFileStream, ftBlob);[/b]
    // execute the sql
    qCmd.Execute;

    // refresh the table so it shows the new picture
    RefreshTable;
  finally
    vFileStream.Free;
  end;
end;

Reading Image from Dataset
Here is the code in our demo project to read image from the dataset (in this case tblMovies).
procedure TForm1.LoadPicture;
var
  BS: TStream;
  vGraphic: TGraphic;
begin
  // clear the currently displayed picture
  Image1.Picture.Graphic := nil;
  // do we have something to display?
  if tblMovies.IsEmpty then Exit;

  // Get a TBlobStream instance from the content of field Picture of tblMovies, with read-only access
  BS := tblMovies.CreateBlobStream(tblMovies.FieldByName('Picture'), bmRead);
  try
    // create the object to parse the image information into jpg picture
    vGraphic := TJPEGImage.Create;
    try
      // give the content of our TBlobStream to the jpg image object
      vGraphic.LoadFromStream(BS);
      
      // give the jpg image object to TImage to display
      Image1.Picture.Graphic := vGraphic;
    finally
      vGraphic.Free;
    end;
  finally
    BS.Free;
  end;
end;

Wednesday, 20 March 2013

Menghitung jumlah kata dalam kalimat


ArRady Fuad Ar-Radhi
jumlah kata dapat dihitung dengan memisahkannya pada spasi,,
klo dengan Tstringlist malah sangat mudah,
setelah di delimiter,, hitung aja count dr Tstringlist tersebut
Like  14 March at 13:05
Imam Chalimi Bin Moeslim
procedure TForm1.Button1Click(Sender: TObject);
var
sl: TStringList;
begin
sl:=TStringList.Create;
sl.LineBreak:=' '; // spasi
sl.Text:=Edit1.Text;
ShowMessage(IntToStr(sl.Count)+' kata');
sl.Free;
end;
Like  14 March at 13:05
ArRady Fuad Ar-Radhi
hehe,, langsung ada contoh dr bang imam :D
Like  14 March at 13:05
Like  14 March at 13:06
Mokhammad Ramdhani Raharjo
maksud saya jika saya mempunyai kata "Indonesia" terus saya cek di kalimat atau di halaman yang penuh karakter bahkan ribuan..maka kata indonesia jumlahnya misal 50,dan terus kata lainya
Like  14 March at 13:07
Imam Chalimi Bin Moeslim
hahaha .. salah persepsi dengan pertanyaannya :(
Like  14 March at 13:08
ArRady Fuad Ar-Radhi
wakakaka,, pake POS atau ANSIPOS kayaknya bisa ...
tp sepertinya bang Imam Chalimi Bin Moeslim punya jurus itu 8)
Like  14 March at 13:08
Like  14 March at 13:09
Like  14 March at 13:10
Viko Wong Jowo
nyemak, untuk curi jurus -_-'
Like  14 March at 13:13
Mokhammad Ramdhani Raharjo
Lagi bikin aplikasi klasifikasi paper/jurnal dan sejenisnya...untuk perbidang ilmu
Like  14 March at 13:13
Imam Chalimi Bin Moeslim
kata yg dicari di edit1 .. misalnya indonesia
kalimat yg dicari di memo1 .. misalnya ... banyak gak bisa ngitung :v
procedure TForm1.Button1Click(Sender: TObject);
var
s: string;
i,n: Integer;
begin
s:=Memo1.Text;
n:=0;
repeat
i:=pos(Edit1.Text,s);
if i=0 then
Break;
Inc(n);
Inc(i,Length(Edit1.Text)-1);
Delete(s,1,i);
until False;
ShowMessage('ditemukan '+IntToStr(n)+' kata');
end;
Like  14 March at 13:14
Mokhammad Ramdhani Raharjo
thanks Bang Imam Chalimi Bin Moeslim nanti itu saya kembangkan
Like  1  14 March at 13:15
Like  14 March at 13:17
Viko Wong Jowo
siap pakai jurus curian, maap y pak.. :D
Like  14 March at 13:20
Imam Chalimi Bin Moeslim
kalo nyuri itu gak kelihatan, kalo ini namanya merampok ... :v
Like  14 March at 13:20
Mokhammad Ramdhani Raharjo
mungkin ada yang mw angkat masalah ni buat skipsinya hehe pi PKL dulu di LIPI atau Dikearsipan pendidikan
Like  14 March at 13:22
Viko Wong Jowo
tpi kliatany yg dirampok iklas tuh.. ;)
Like  14 March at 13:23
Mokhammad Ramdhani Raharjo
Silahkan saja. ni konsep sederhana nya..lum lagi kalo ketemu kata awalan ,imbuhan harus ,Masalh pasing, DLL. =D
Like  14 March at 13:25
Viko Wong Jowo
lgi nyari judul berbau delphi belum nemu.. :(
pak Imam ada saran bwt adek? hahaa

bang Mokhammad Ramdhani itu aplikasi konsep'ny gmn si?
Like  14 March at 13:25
Ninofelino Felino
simplenya bisa mempergunakan "dhtml parse" , karena dalam HTML untuk mengitung paragraf harus di ambil dahulu kata diatara tag <p> dan </p> , barus setelah itu diproses dengan tstringlist
Like  1  14 March at 13:26
ArRady Fuad Ar-Radhi
yg berbau delphi ya?
ada "SIstem Parfum berbau delphi" :v
Like  14 March at 13:26
ArRady Fuad Ar-Radhi
yg berbau delphi ya?
ada "SIstem Parfum berbau delphi" :v
Like  14 March at 13:27
Viko Wong Jowo
baunya delphi kyk gmn y..!! :\'
Like  14 March at 13:28
Mokhammad Ramdhani Raharjo
jadi entar paper/jurnal/sejenis yg banyak halaman(PDF,MS WORD, DLL)
saya scan maka si aplikasi akan menggolongkan itu masuk ilmu
apa.tapi dengan ketentuan yang ada
Like  14 March at 13:29
Mokhammad Ramdhani Raharjo
sedikit berbau kecerdasan buatan
Like  14 March at 13:29
Ninofelino Felino
kalau mau buiat aplikasi seperti itu , buat structur XHTML ,XLT,XSY baru dipecah dengan XDOM nya delphi
Like  1  14 March at 13:33
Viko Wong Jowo
oya jadi kpikiran kata tmen, andai bisa bwt aplikasi utk mendeteksi isi file document,mp3 or dll yg sama dengan nma file beda, ukuran file beda!!
Like  14 March at 13:33
Like  14 March at 13:34

Best Post This Year

Install Fortesreport community Delphi 7 dan RX Berlin

Download  Pertama2 kita harus punya file installernya terlebih dahulu, download  https://github.com/fortesinformatica/fortesrepo...

Total Pageviews

© 2014 Fajar Priyadi. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates | Powered By Blogger
TOP