Originally from: http://www.delphitop.com/html/kongjian/2079.html
The TClientDataSet control inherits from Tdataset, whose data store file format has a. cds extension, and is a control based on file-type data storage and manipulation. The control encapsulates the interfaces and functions that manipulate the data, and does not rely on the above-mentioned database drivers, basically satisfying the needs of a stand-alone "thin" database application.
1. Introduction to basic properties and methods of TClientDataSet
1). Fielddefs: Field Definition List Properties
The developer can edit the field by clicking the Property Edit button in the property editor, or by right-clicking the Fields Editor menu in the pop-up menu on the control. When this property is set, it is actually the equivalent of defining the structure of the table, and if you want to load the structure and data of an existing data table, you can select the Assign Local Data menu in the pop-up menu by right-clicking From the Pop-up dialog box, select the dataset control name that is already connected to the database in the current form (the data set control that you want to apply must already be placed in the current form and the activation is turned on).
Use Note:
For a custom field name table, the control still cannot be opened when the property is finished editing. You must right-click the control and select the Create DataSet menu in the pop-up menu so that the control can be activated to open and use after the dataset is created, based on the list of fields edited above. Otherwise, a similar "clientdataset1:missing data provider or data packet will appear." Errors (including during run time, the runtime can invoke the control's CreateDataSet method to dynamically define fields and tables).
2). FileName Property
Description: The name of the data store file.
Because the control is a file-based data manipulation control, you must specify the data file name you are manipulating (the default extension name. CDs) to open and activate the control for data editing.
Example 1: Use this property to open the specified. cds file
Var
path:string;
Begin
Path: = Extractfilepath (Application.exename); Get the executable file path
Cdataset1.filename: = Path + ' Test.cds ';
Cdataset1.open;
End
3). CreateDataSet method
Description: This method uses the field name table in Fielddefs to create a dataset, which is commonly used to dynamically define tables.
Example 2: Dynamically creating a DataSet with a name and age of two fields.
Create a Field Name table
CDataSet.FieldDefs.Clear;
With CDataSet.FieldDefs.AddFieldDef do
Begin
Name: = ' name ';
Size: = 10;
DataType: = ftstring;
End
With CDataSet.FieldDefs.AddFieldDef do
Begin
Name: = ' age ';
DataType: = Ftinteger;
End
Dynamically creating datasets
Cdataset.createdataset;
Activating and opening the dataset
Cdataset.open;
4). Open method
Description: Opens and activates the dataset control for data editing.
A. If the filename attribute is specified, the control can be opened and activated directly using the open method, as shown in Example 1.
B. If you do not specify the FileName property, you can use the example 2 method to dynamically create and open a dataset to manipulate the data.
5). LoadFromFile and SaveToFile
Description: Loads the table structure and data from the file and stores the data to the file. This method is similar to opening new files and saving features in Word.
Example 3: Storing data from a dataset in a specified file
Cdataset.savetofile (' C:/windows/desktop/test.cds ');
6). First (to top), Prior (forward), Next (backward), last (to tail), edit (Edit), Cancel (cancel edit), Post (Save), insert (insert record), Append (add record), delete (delete), Common methods for data sets such as refresh (data refresh)
Note: When the FileName property is specified, its Post method can store the data in the specified file, similar to its SaveToFile method, and the Post method stores the data only in RAM if no storage file name is specified. Other methods, with general data set controls, are used in a slightly different way.
7). Filter, Filtered: Filtering Filter Properties
Description: Used to filter records for a specified condition, using the same general data set control, slightly.
Example 4: Screening for male-sex records in an open data set that has been activated
Cdataset.close;
Cdataset.filter: = ' gender = ' + ' male ' + ';
cdataset.filtered: = True;
Cdataset.open;
2. Considerations for publishing applications that use the TClientDataSet control:
As mentioned earlier, a program that uses the TClientDataSet control does not require any database drivers when it is published, greatly saving the size of the installation file. However, do not forget to publish the program with the Windows System directory Midas.dll (257KB) with the application (running must), otherwise, the program will still not function properly.
Iii. concluding remarks
By using the TClientDataSet control in Delphi, both the application can be completely detached from the database driver, and the simple and easy-to-use features of the general data set control are realized, which provides a technical method and means for writing "thin" database application.
The above procedure is tested and passed under Pwindows98,delphi5.
TClientDataSet in the three-storey structure, the status of TClientDataSet is immeasurable, her use is correct or not, is very critical, this article from the following aspects of her use, I hope to help you.
1. Dynamic indexing
Procedure Tform1.dbgrid1titleclick (Column:tcolumn);
Begin
if (not column. Field is Tblobfield) Then//tblobfield cannot be indexed, binary
Clientdataset1.indexfieldnames:=column. Field.fieldname;
End
2. Implementation of master-slave table in multi-layer structure
Set the main table Clientdataset1.packetrecord to-1, all records
Set from table Clientdataset1.packetrecord to 0, current record
3.Taggregates use
(1) In field edit, add new field type is aggregates
After setting expression (express test)
Set Active:=true to
Use the Dbedit field for the former
(2) using the Aggergates attribute add design expression test
Call
ShowMessage (Floattostr (ClientDataSet1.Aggregates.Count));
ShowMessage (Clientdataset1.aggregates.items[0]. Value);
4. Do not BDE in a single-tier database
Use Clientdataset instead of table to load CDs with Clientdataset Loadfilename
DB or DBF in place of table TableName
The original program modification method:
Add a clientdataset, use right-click Assign locate data
After SaveToFile, then loadfromfile, delete table after
Set the DataSource of the original connection table to Clientdataset
The only thing to note is: To copy Midas.dll to system or current directory
5. How to implement the briefcase with three-layer structure
Set 1:filename (*.CDS) 2.remote server at the same time
6. Can assign a value to data (value from another dataset)
Clientdataset2.data:=clientdataset1.data;
Clientdataset2.open;
Or
Clientdataset2.clonecursor (clientdataset1,true);
Clientdataset2.open;
7. Additional data obtained
The client program requests data from the application server. If TClientDataSet's
The Fetchondemand property is set to True,
The client program automatically retrieves the value of an attached packet, such as a BLOB field, or the contents of a nested table, as needed.
Otherwise
The client program needs to explicitly call Getnextpacket in order to obtain these additional packets.
Clientdataset Packetrecords Set the number of records obtained at one time
8.ClientDataSet and server-side query connection method
(1) SQL content is empty
Clientdataset1.close;
clientdataset1.commandtext:=edit1.text;//that is SQL content
Clientdataset1.open;
For no application server settings filter such as: Country like ' A% '
Filtered=true to enable SQL functionality
(2) Parameters
such as the SQL for server query
SELECT * FROM Animals
Where name like:d D
Then: Client Clientdataset
Var
Pm:tparam;
Begin
Clientdataset1.close;
clientdataset1.providername:= ' DataSetProvider1 ';
Pm:=tparam.create (nil);
Pm. name:= ' DD ';
Pm. datatype:=ftstring;
ClientDataSet1.Params.Clear;
ClientDataSet1.Params.AddParam (PM);
ClientDataSet1.Params.ParamByName (' DD '). Asstring:=edit1. Text;
Clientdataset1.open;
Pm. Free;
End
9. Update management of data
(1) SavePoint save data status so far, can be restored to this state
Var
Pp:integer;
Begin
Pp:=clientdataset1.savepoint;
Clientdataset1.edit;
Clientdataset1.fieldbyname (' name '). asstring:= ' the proverb ';
Clientdataset1.post;
Table1. Refresh;
End
Recovery point
CLIENTDATASET1.SAVEPOINT:=PP;
(2) Cancel,revertrecord
Cancels the modification of the current record, only suitable for no post, if post, call
Revertrecord
(3) CancelUpdate
Cancel all modifications to the database
(4) Undolastchange (Boolean), Changecount
Cancels the last modification, which allows for continuous undo
Parameter is true: cursor to recovery place
False: The cursor does not move at the current position
Changecount returns the number of times a record has been modified, one record modified more than once, and returned only once
But Undolastchange only undo once.
10. Writable Recno
Recno for ttable and Tquery are read-only, while TClientDataSet Recno can be read and writable
Clientdataset1.recno:=5; is set fifth record as current record
11. Data Retention
Use post to update data for table
The ClientDataSet1 post only updates the memory data, to update the server data to use
Applyupdates (Maxerrors:integer), he has a parameter that is allowed to emit the wrong
Times, 1 means countless times, standing at 0 with Simpleobjectbroker for automatic fault tolerance and load balancing
======================================================
A factor affecting the speed of clientdataset processing
TClientDataSet is a very good control when Delphi develops a database. Has a very powerful function.
I often use Clientdataset to do memorydataset. You can also save the Clientdataset data as XML so that you can do a simple local database use. There's a lot more to say. In the process of using clientdataset about how to improve the speed of the problem, I personally a little bit of experience and share with you.
Normally, we usually use
... Clientdataset-->datasource-->dbcomponent
Such a structure, the processing of data when the direct operation of Clientdataset. But most dbcomponet will respond to clientdataset changes immediately. If you are inserting a lot of data into Clientdataset, Dbcomponent will respond a few times, and the response process will vary depending on the control, speed, and number of processes. This affects the execution efficiency of the program. So in the process of Clientdataset, I'm using Clientdataset.disablecontrols and Clientdataset.enablecontrols methods: Turns on and off the data display relationship between Dbcomponent and Clientdataset.
For example:
Clientdataset. Disablecontrols;
...
For I: = 0 to 10000 do
Begin
Clientdataset.append;
...
Clientdataset.post;
End
...
Clientdataset.enablecontrols
...
When you do this, you will find that the processing speed is exponentially higher than when you have not used the method before.
Clientdataset Data Lookup.
The tips and tricks I've introduced are examples of clientdataset, and can be applied to other datasets as well. Nonsense will not be said more. Let's look at the code first and then summarize it.
1.Scanning Scan Data Lookup
This is the simplest and most direct and slowest way to traverse all the data:
Procedure Tform1.scanbtnclick (Sender:tobject);
Var
Found:boolean;
Begin
Found: = False;
Clientdataset1.disablecontrols;
Start;
Try
Clientdataset1.first;
While not clientdataset1.eof do
Begin
If Clientdataset1.fields[fieldlistcombobox.itemindex].value =
SearchText Then
Begin
Found: = True;
break;
End
Clientdataset1.next;
End
Done;
Finally
Clientdataset1.enablecontrols;
End
If Found then ShowMessage (SearchText +
' Found at record ' + inttostr (CLIENTDATASET1.RECNO))
Else
ShowMessage (Scanforedit.text + ' not found ');
End
2.Finding Looking for data
The oldest, but fastest way to find.
Use Findkey/findnearest to find one or more qualifying data, but the field you are looking for must be a indexfield. As you can see, this index-based lookup rate is very fast.
Procedure Tform1.findkeybtnclick (Sender:
TObject);
Begin
Start;
If Clientdataset1.findkey ([SearchText]) then
Begin
Done;
STATUSBAR1.PANELS[3]. Text: = SearchText +
' Found at record ' +
IntToStr (CLIENTDATASET1.RECNO);
End
Else
Begin
Done;
STATUSBAR1.PANELS[3]. Text: =
SearchText + ' not found ';
End
End
Procedure Tform1.findnearestbtnclick (Sender:tobject);
Begin
Start;
Clientdataset1.findnearest ([SearchText]);
Done;
STATUSBAR1.PANELS[3]. Text: = ' The nearest match to ' +
SearchText + ' found at record ' +
IntToStr (CLIENTDATASET1.RECNO);
End
3.Going positioning
Gotokey/gotonearest and Findkey/findnearest are basically no different. It is also a lookup based on index. The only difference is how you define your search. There are also differences in code:
Clientdataset1.setkey;
Clientdataset1.fieldbyname (Indexfieldname). Value: = SearchText;
Clientdataset1.gotokey;
is equivalent to
Clientdataset1.findkey ([SearchText]);
To use both of these index-based lookups, you also need to understand the Clientdataset and index mechanisms. The index mechanism is not described in detail here. A basic principle, to have index, to find.
4.Locating Finding data
2, 32 search methods are based on index, but in real-world applications, you might find field outside of Indexfield. Then we can use locate. But the search speed is not 2, 32 kinds of fast. For example: If you look for a record 9000/10000,locate need 500ms,scanning need to >2s,findkey as long as 10ms (but when you open Clientdata, set index needs 1s).
Procedure Tform1.locatebtnclick (Sender:
TObject);
Begin
Start;
If Clientdataset1.locate (' Field1,field2. ', vararrayof[' value1,value2: '], []) then
Begin
Done;
STATUSBAR1.PANELS[3]. Text: =
' Match located at record ' +
IntToStr (CLIENTDATASET1.RECNO);
End
Else
Begin
Done;
STATUSBAR1.PANELS[3]. Text: = ' No match located ';
End
End
Summary:
Clientdataset provides a lot of ways to find data. But each has its own merits and demerits.
The above example has start; and done, if you are interested, you can add a timing point for the speed test.
Scanning is the simplest, but slowest, because it's slower, and you have to use the Clientdataset.disablecontrols and Clientdataset.enablecontrols methods (as I said in the previous article).
Findkey/findnearest (gotokey/gotonearest) code is much, but very fast. You must use index, and the difference is that the index required for find must be set up, and Goto can establish index on first use.
Locate is the easiest to use and does not need index, but speed does not find Fast.
Introduction to basic properties and methods of TClientDataSet