Multi-layer database development 6: What is a dataset

Source: Internet
Author: User
Tags dbase
Chapter 6 What is a dataset
Delphi 4 has four types of Standard dataset components: tTable, tquery, tstoredproc, and tclientdataset. These dataset components are inherited from a common basic class tdataset, where only tclientdataset is inherited directly from tdataset, while tTable, tquery, and tstoredproc are directly inherited by tdbdataset, the upper level of tdbdataset is tbdedataset, and that of tbdedataset is tdataset. The inheritance relationships between these classes can be expressed in Figure 6.1.
Figure 6.1 inheritance relationship of a dataset
Tdataset is the abstract base class of all datasets. Most of its attributes and methods are virtual or abstract. Virtual methods can be overloaded by Derived classes. The so-called abstract method means that these methods can be called only after they are declared and not defined. Different Derived classes can have different definitions.
Because tdataset contains abstract methods, you cannot directly create an instance of tdataset. Otherwise, a runtime error may occur.
In terms of functions, tdataset attributes and methods can be divided into the following parts: open and Close datasets, browse records, edit data, manage bookmarks, control connections, access fields, Record Buffer Management, filtering, and events.
6.1 open and close a dataset
Before performing any operations on a dataset, you must first open the dataset. To open a dataset, you can set the active attribute to true. For example:
Custtable. Active: = true;
You can also call the OPEN function, for example, custquery. open;
To disable a dataset, set the active attribute to false or call the close function.
6.2 dataset status
The state attribute of a dataset determines the operations that can be performed on a dataset. For example, if a dataset is disabled and its status is dsinactive, no data in the dataset can be accessed.
6.2.1 state attributes
The state attribute is read-only and the possible values of the state attribute are listed below:
. The dsinactive dataset is disabled and cannot access its data;
The. dsbrowse dataset has been opened. You can browse the data but cannot modify the data;
. Dsedit is editable at this time. You can modify the data;
. Dsinsert a new record can be inserted at this time;
. Dssetkey is only applicable to tTable and tclientdataset. You can set the range and key value, and call the gotokey function;
. Dscalcfields is processing the oncalcfields event. The value of the non-calculated field cannot be modified;
. Dscurvalue is used internally;
. Dsnewvalue is used internally;
. Dsoldvalue is used internally;
. Dsfilter is filtering.
When a dataset is opened, its state attribute is set to dsbrowse. In the future, the value of state attribute will automatically change as the application operates.
To enable the dataset to enter the dsbrowse, dsedit, dsinsert, or dssetkey status, you must call the corresponding method.
For example, to enable the dataset custtable to enter the dsinsert state, the program example is as follows:
Procedure tform1.insertbuttonclick (Sender: tobject );
Begin
Custtable. insert; {dsinsert status}
Addresspromptdialog. showmodal;
If addresspromptdialog. modalresult: = mrok then
Custtable. Post; {restore to dsbrowse status}
Else
Custtable. Cancel; {restore to dsbrowse status}
End;
From the above example, we can see that some operations will automatically change the dataset to the dsbrowse State. For example, if the post function is called successfully, the dataset will be restored to the dsbrowse State. If the post function is not called successfully, the dataset remains in the original state. You can also call Cancel to restore the dataset to the dsbrowse state.
If you set the active attribute to false or call close, the dataset enters the dsinactive state. For example, the following two lines of code are equivalent:
Custtable. Active: = false;
Custtable. close;
Some statuses such as dscalcfields, dscurvalue, dsnewvalue, dsoldvalue, and dsfilter cannot be controlled by the application, but are automatically set by the dataset as needed. For example, when an oncalcfields event is being processed, it automatically enters the dscalcfields status. When you exit the handle for processing the oncalcfields event, the dataset is automatically restored to its original state.
When the status of a dataset changes, the onstatechange event of the tdatasource component is triggered if the dataset is specified by the dataset attribute of the tdatasource component.
The following describes in detail the status of a dataset and how to enter these statuses.
6.2.2 dsinactive status
When the dataset is closed, it is in the dsinactive state. In this case, you cannot access any of its data.
To enable the dataset to enter the dsinactive status, set the active attribute to false or call close. The beforeclose event is triggered before the dataset is closed. When the dataset is closed, the afterclose event is triggered. If you call close when the dataset is in the dsedit or dsinsert status, you should prompt the user whether to approve or cancel it in the handle for processing the beforeclose event. The program example is as follows:
Procedure custtable. verifybeforeclose (Dataset: tdataset)
Begin
If (custtable. State = dsedit) or (custtable. State = dsinsert) then
Begin
If messagedlg ('Do you agree to the modification? ', Mtconfirmation, mbyesno, 0) = mryes then
Custtable. post;
Elsecusttable. Cancel;
End;
End;
6.2.3 dsbrowse status
When a dataset is opened, it is always in the dsbrowse State. At this time, records in the dataset can be displayed, but records cannot be edited or inserted.
The dsbrowse status can be considered as the basic status of the dataset. In this status, it can enter another status. For example, calling the insert or append function will change the status of the dataset from dsbrowse to dsinsert (Of course, this also depends on other factors, such as the value of the canmodify attribute ), call setkey to change the data set from dsbrowse to dssetkey state.
Tdataset has two methods to bring the dataset back to the dsbrowse state. One is cancel, which will cancel the current editing, insertion, search, and other operations, so that the dataset will return to the dsbrowse state. The other is post, which will try to save the modified data to the dataset. If it succeeds, the dataset will return to the dsbrowse state. If it fails, the dataset will remain in the original state.
6.2.4 dsedit status
If the application wants to modify the data of the dataset, it must first enter the dsedit state. To enter the dsedit status, you can call edit. However, calling edit does not guarantee that it enters the dsedit state, which depends on the value of the canmodify attribute. If this property returns true, the dataset can be read and written.
For the tTable component, if the readonly attribute is set to true, the canmodify attribute returns false. For the tquery component, if the requestlive attribute is set to false, the canmodify attribute returns false.
Even if the dataset enters the dsedit status, it does not mean that the user can modify the data. The readonly attribute of the data control must be set to false. In addition, for SQL databases, whether a user can modify data depends on whether the user has the permission to modify data.
To return the status from dsedit to dsbrowse, you can call the cancel, post, or delete function. If the post and delete functions are not called successfully, the status of dsedit remains unchanged.
In the data control, when the user changes the data and removes the input focus, it is equivalent to calling the post function, which will return the dataset to the dsbrowse state.
6.2.5 dsinsert status
If the application needs to insert a new record, it must first enter the dsinsert state. To enter the dsinsert status, you can call the insert or append function. However, calling insert or append does not guarantee that the data enters the dsinsert state. It depends on whether the value of the canmodify attribute returns true.
Even if the dataset enters the dsinsert status, it does not mean that the user can insert records. The readonly attribute of the data control must be set to false. In addition, for SQL databases, whether a user can insert records depends on whether the user has the permission to modify data.
To return data from the dsinsert status to the dsbrowse status, you can call the cancel, post, or delete function. If the post function is not called successfully, the dsinsert status remains unchanged.
In the data control, when the user changes the data and removes the input focus, it is equivalent to calling post, which will return the dataset to the dsbrowse state.
6.2.6 dssetkey status
You can call locate and lookup to search for specific records in the dataset. For the tTable component, you can also call gotokey, gotonearest, findkey, or findnearest to search for specific records in the table. Before calling the preceding method, you must first set the dataset to the dssetkey state. To enable the dataset to enter the dssetkey status, call setkey. After the preceding method is called, The dataset returns to the dsbrowse status.
In addition, you can filter datasets. For the tTable component, you can also set the range in advance. Before filtering and range operations, you must first enter the dssetkey status.
6.2.7 dscalcfields status
When an oncalcfields event is triggered, the dataset enters the dscalcfields state. In the handle for processing the oncalcfields event, the value of "calculated field" should be given.
In the dscalcfields state, the application cannot modify the values of other fields except the "calculated field". If the values of other fields change, the oncalcfields event is triggered, this leads to an infinite loop.
After the oncalcfields event is processed, the dataset returns to the dsbrowse status.
6.2.8 dsfilter status
When the onfilterrecord event is triggered, the dataset enters the dsfilter state. In this status, you are not allowed to modify the records of a dataset. Otherwise, filtering cannot be performed correctly.
After the onfilterrecord event is processed, the dataset returns to the dsbrowse status.
6.2.9 dsnewvalue, dsoldvalue, or dscurvalue
When the cache update is allowed, When you modify a dataset record, the dataset may enter the dsnewvalue, dsoldvalue, or dscurvalue status. In these three states, you can access the current value through the newvalue, oldvalue, or curvalue attribute of the field (tfield.
The preceding three States are used internally by Delphi 4, and applications cannot actively enter the preceding three states.
6.3 Overview
Each active dataset has a pointer pointing to the current record. Many operations on datasets are performed on the current record, and many data controls only display the data of the current record. Therefore, it is very important to know the location of the current record in the database application.
Database applications often need to change the location of the current record. In this case, the following methods are used:
. First makes the first record the current record;
. Last makes the last record the current record;
. Next makes the next record the current record;
. Prior makes the previous record the current record;
. MoveBy makes records that are several rows away from the current record into the current record.
In addition, Delphi 4 has a tdbnavigator component dedicated for viewing records. It uses buttons to implement the above method.
In addition to the preceding method, tdataset also has two read-only Boolean attributes used to determine the location of the current record. One is BOF. If this attribute returns true, indicates that the start position of the dataset has been reached. The other is EOF. If this attribute returns true, it indicates that it has reached the end of the dataset.
6.3.1 first and last
Call the first function to make the first record of the dataset the current record and set the BOF attribute to true. If the first record is already the current record, first will do nothing. The program example is as follows:
Custtable. first;
Call the last function to make the last record of the dataset the current record and set the EOF attribute to true. If the last record is already the current record, the last record will do nothing. The program example is as follows:
Custtable. Last;
There are two buttons on the navigator implemented using the tdbnavigator component, which correspond to first and last respectively.
6.3.2 next and prior
The next function can be called to make the next record the current record. If the current record is already the last record of the dataset, next will do nothing. The program example is as follows:
Custtable. Next;
Calling prior can make the previous record the current record. If the current record is already the first record of the dataset, Prior will do nothing. The program example is as follows:
Custtable. Prior;
6.3.3 moveBy
Call the moveBy function to make another record in the dataset the current record. The record is several rows away from the current record. MoveBy needs to pass a parameter to specify the number of rows separated by each other. Positive numbers indicate moving to the direction in which the number of records increases, and negative numbers indicate moving to the direction in which the number of records decreases. The program example is as follows:
Custtable. moveBy (-2 );
MoveBy returns the number of actually moved rows. The returned value may be different from the parameter passed to moveBy.
Note: In a multi-user environment, other users may be modifying, inserting, or deleting records. In this way, a record is five rows away from the current record, now it may be four or six rows, or even the record does not exist, because other users modify the data of the record or delete the record.
6.3.4 attributes of EOF and BOF
Tdataset has two read-only attributes, EOF and BOF, which are used to determine whether the end and start of the dataset are reached. These two attributes are often used to traverse all records of a dataset.
If the EOF attribute returns true, it indicates that it has reached the end of the dataset.
When you perform the following operations, the EOF attribute is set to true:
. Open an empty dataset;
. Called last;
. Next is called, and now it is in the last record of the dataset;
. Setrange is called, and the range is invalid.
In addition to the preceding conditions, the EOF attribute returns false.
The EOF attribute is usually used in a loop. Each call to next determines the EOF attribute to avoid operations on records that do not exist. The program example is as follows:
Custtable. disablecontrols;
Try
Custtable. first;
While not custtable. EOF do
Begin
...
Custtable. Next;
End;
Finally
Custtable. enablecontrols;
End;
The code above also demonstrates how to temporarily disable the data control from refreshing when traversing all records of a dataset. Call disablecontrols to prohibit refresh before traversing all records of a dataset. This will speed up the traversal, because refresh also takes time. After the traversal, you should call enablecontrols to restore the refresh.
Enablecontrols is best called in the finally part of the try... Finally structure. This ensures that the Refresh can be restored even if an exception occurs during the time.
If the BOF attribute returns true, it indicates that it has reached the beginning of the dataset.
When you perform the following operations, the BOF attribute is set to true:
. Open a non-empty dataset;
. First is called;
. Prior is called, and the first record in the dataset is now called.
In addition to the preceding conditions, the BOF attribute returns false. Like the EOF attribute, the BOF attribute is usually used in a loop. Every time a prior is called, The BOF attribute must be judged to avoid operations on records that do not exist. The program example is as follows:
Custtable. disablecontrols;
Try
While not custtable. bof do
Begin
...
Custtable. Prior;
End;
Finally
Custtable. enablecontrols;
End;
6.4 signatures
Bookmarks are used to mark a specific position of a dataset so that you can quickly and conveniently return to that position. Tdataset provides several attributes and methods for managing bookmarks.
If the bookmark attribute is read, the bookmark of the current record is returned. If you write the bookmark attribute, it can make a specified bookmark the current bookmark.
Several functions related to bookmarks in tdataset are virtual. tbdedataset, a derived class of tdataset, redefined these methods, including:
. Bookmarkvalid: determines whether a bookmarks are legal;
. Comparebookmarks: checks whether two bookmarks are the same;
. Getbookmark creates a bookmarks to mark the current record;
. Gotobookmark returns to the position marked with getbookmark;
. Freebookmark: delete a bookmarks.
To create a bookmarks, declare a variable of the tbookmark type, and call the getbookmark function to create a bookmarks that mark the current record. A variable of the tbookmark type is actually a non-type pointer.
Before calling gotobookmark, it is best to call bookmarkvalid to determine whether the bookmarks are legal, because the records marked by the bookmarks may have been deleted. If bookmarkvalid returns true, the bookmarks are valid. You can call gotobookmark to jump to the position marked by the bookmarks.
You can call comparebookmarks to check whether the two bookmarks are the same. If the two bookmarks are different, this function returns 1. If both bookmarks are the same or both are nil, this function returns 0.
Gotobookmark needs to pass a parameter, that is, bookmarks.
Freebookmark is used to delete a bookmarks. When a bookmark is used, it should be deleted in time because it is also a resource.
The following code demonstrates the usage of bookmarks:
Procedure dosomething (const TBL: tTable) varbookmark: tbookmark;
Begin
Bookmark: = TBL. getbookmark;
TBL. disablecontrols;
Try
TBL. first;
While not TBL. EOF do
Begin
...
TBL. Next;
End;
Finally
TBL. gotobookmark (bookmark );
TBL. enablecontrols;
TBL. freebookmark (bookmark );
End;
End;
6.5 search for specific records
You can call the locate and lookup functions to search for specific records in the dataset.
Locate is used to locate a specific record in the dataset and make the record the current record. Three parameters are required for locate. The first parameter is the keyfields parameter, which is used to specify the fields to be searched, and the second parameter is the keyvalues parameter, which is used to specify the values of each field, the third parameter is the options parameter, which is used to set search options.
The following example shows a record with the company field value "professional Ltd:
VaR
Locatesuccess: Boolean;
Searchoptions: tlocateoptions;
Begin
Searchoptions: = [lopartialkey];
Locatesuccess: = custtable. Locate ('company', 'professional Ltd. ', searchoptions );
End;
If locate finds a qualified record, the record is changed to the current record and true is returned. If no matching record is found in the locate, false is returned.
For locate, the more fields specified by the keyfields parameter, the more accurate the search condition. If the keyfields parameter requires multiple fields to be specified, separate them with semicolons. Because the data types of fields may be different, keyvalues is a parameter of the variant type. If the keyfields parameter specifies multiple fields, the keyvalues parameter must be a mutable array. The program example is as follows:
With custtable do
Locate ('Company; contact; phone', vararrayof (['sight diver ', 'P']), lopartialkey );
Lookup is very similar to locate. It is also used to search for specific records in a dataset. The difference is that if a matched record is found, lookup can return the values of several fields in the record.
Three parameters are required for lookup. The first parameter is the keyfields parameter, which is used to specify the fields to be searched, and the second parameter is the keyvalues parameter, which is used to specify the values of each field, the third parameter is the resultfields parameter, which is used to specify the values of the fields to be returned.
In the following example, the company field is searched for a record with the value of "professional Ltd." In custtable, and the values of the fields such as company, contact, and phone are returned:
VaR
Lookupresults: variant;
Begin
With custtable do
Lookupresults: = Lookup ('company', 'professional divers, Ltd. ', 'Company; contact; phone ');
End;
If the resultfields parameter specifies multiple fields, lookup returns an array of variable types. If no matching record is found, lookup returns an empty array. The program example is as follows:
VaR
Lookupresults: variant;
Begin
With custtable do
Lookupresults: = Lookup ('Company; city', vararrayof (['sight diver ',
'Christiansted ']), 'Company; addr1; addr2; State; zip ');
End;
6.6 over Filter
An application is often only interested in some records of a dataset. For example, an application may only be interested in customers from Guangdong in a customer table. In this case, you can use the filtering technology to filter records that meet specific conditions.
However, for a dataset with many fields, it is best to use query.
6.6.1 allow filtering
To filter a dataset, you must first specify the filtering conditions, set the filteroptions attribute to set relevant options (optional), and then set the filtered attribute to true. If you do not want to filter data in the future, set the filtered attribute to false.
You can specify two filtering conditions: one is to set the filter attribute, and the other is to provide filtering conditions in the handle for processing the onfilterrecord event.
The filter attribute is suitable for running. It can dynamically specify filtering conditions and change filtering conditions as needed. However, the filter attribute is a string and the filter conditions are relatively simple. Although operators can be used to form a composite conditional expression, they are limited to several common operators. More importantly, only the existing field names and constants in the dataset can appear in the expressions specified by the filter attribute, and no other data can appear.
While the onfilterrecord event is much more flexible, it can specify filtering conditions during the design period. In the handle for processing the onfilterrecord event, you can specify any filtering conditions, which can be complex.
6.6.2 filter attributes
The filter attribute is a string. You can set the filter attribute as follows:
Dataset1.filter: = '''state' = ''ca ''';
You can also set the filter attribute as follows:
Dataset1.filter: = edit1.text;
The above line of code allows users to enter filtering conditions themselves. You can even combine the above two lines of code:
Dataset1.filter: = '''state' = '+ edit1.text;
After a filter condition is set, the filter is valid if the filtered attribute is set to true.
You can use comparison and logical operators to construct a composite filter condition. These operators include:
. <Less;
.> Greater;
.> = Greater than or equal;
. <= Less than or equal;
. = Equals;
. <> Not equal;
The expressions on both sides of. And must be true;
The. Not expression cannot be true;
Either of the. or expressions is true.
In the following example, The and operator is used to limit that the custno field must be greater than 1400 and less than 1500:
(Custno> 1400) and (custno <1500 );
Note: When the filtered attribute is set to true, the records modified and inserted by the user may not meet the filtering conditions. At this time, the records that conflict with the filtering conditions will be rejected.
6.6.3 onfilterrecord event
When the filtered attribute is set to true, each record in the dataset triggers an onfilterrecord event, so that you have the opportunity to decide whether to filter records.
There is a Boolean accept parameter in the handle for processing the onfilterrecord event. setting this parameter to true indicates accepting the record, and setting this parameter to false indicates filtering out the record. The program example is as follows:
Procedure tform1.table1filterrecord (Dataset: tdataset;
VaR accept: Boolean );
Begin
Accept: = dataset ['state'] = 'CA ';
End;
In the preceding example, only records with the state field value CA are accepted.
Note: Since each record of a dataset triggers an onfilterrecord event, the code for processing the onfilterrecord event should be as short as possible, especially for a large dataset with many records.
Sometimes, the program needs to filter based on a variety of different filtering conditions. You can create multiple handles for onfilterrecord events and dynamically switch the event handle during runtime. The program example is as follows:
Dataset1.onfilterrecord: = newyorkfilter; refresh;
6.6.4 set filtering options
The filteroptions attribute is used to set filtering options. This attribute is a set, which can be an empty set (default) or contain the following elements:
. Focaseinsensitive ignores case sensitivity when comparing strings;
. Fopartialcompare must match all characters for string fields, and partial matching is not allowed.
For example, to ignore the case sensitivity when comparing the state field, you can set it as follows:
Filteroptions: = [focaseinsensitive];
Filter: = '''state' = ''ca ''';
6.6.5 view records in the filtered data set
The filtered dataset is actually a subset of the original dataset. Tdataset provides four methods to browse records in the filtered data. They are:
. Findfirst makes the first record in the filtered dataset the current record;
. Findlast makes the last record in the filtered dataset the current record;
. Findnext makes the next record in the filtered dataset the current record;
. Findprior makes the previous record in the filtered dataset the current record.
If the preceding four methods are successfully called, true is returned. Otherwise, false is returned. You can check a read-only found attribute to see if the last call was successful.
If a filter condition is set through the filter attribute or onfilterrecord event, and the filtered attribute is set to false, the above four methods are automatically used to temporarily allow filtering and then move the location of the current record, finally, filter is disabled. In other words, the above four methods can ignore how the filtered attribute is set.
If no filter condition is set, the above four methods are equivalent to first, last, next, and prior.
6.7 data revision
Tdataset provides methods to update, insert, and delete records in a dataset. They are:
. Edit enables the dataset to enter the dsedit state;
. Append adds a record at the end of the dataset;
. Insert inserts a record at the current position of the dataset;
. Post tries to write the user's changes to the data set;
. Cancel cancels the user's modification to the data so that the data set is returned to the dsbrowse status;
. Delete: Delete the current record.
6.7.1 enter dsedit status
To edit records of a dataset, you must first enter the dsedit state. To enter the dsedit status, call the Edit function. However, calling edit does not necessarily bring the dataset into the dsedit state, but also depends on the value of the canmodify attribute.
Once the dataset enters the dsedit state, you can modify the value of the current record on the Data Control. When you remove the input focus from the current record, it is equivalent to calling the post function. The program example is as follows:
With custtable do
Begin
Edit;
Fieldvalues ['custno']: = 1234;
Post;
End;
To cancel the pending changes, you can press ESC or click the cancel button on the navigator implemented by the tdbnavigator component.
When cache update technology (the attribute of cachedupdates is set to true) is used, calling post only writes data to the cache, rather than directly writing data to the dataset. To write cached data to a dataset, you must call the applyupdates function.
6.7.2 Insert a new record
To insert a new record in the dataset, you must first enter the dsinsert state. To enter the dsinsert status, you can call the insert or append function. However, calling insert or append does not necessarily bring the dataset into the dsinsert state, but also depends on the value of the canmodify attribute.
Once you enter the dsinsert status, you can insert a new record in the Data Control (generally TDBGrid) and input data to this record.
If you want to insert a new record through programming, pay attention to the difference between insert and append. Insert inserts a new record before the current record, and append adds a new record to the end of the dataset.
After a new record is inserted, you should call post or call applyupdates to write the new record to the dataset if the cachedupdates attribute is set to true.
If the dataset is a paradox or DBASE table with an index already created, the new record is automatically moved to the appropriate location.
If the dataset is not indexed, the new record is inserted to the current position (insert) or end (append) of the dataset ).
6.7.3 delete a record
Calling the delete function will delete the current record and bring the dataset back to the dsbrowse state. If the form contains a tdbnavigator component, you can click "delete" on the navigator to delete the current record. After the current record is deleted, the next record becomes the current record.
If the last record is deleted, the previous record becomes the current record.
6.7.4 modify the entire record
Apart from TDBGrid and tdbnavigator, most data controls can only work on one or several fields of a dataset, rather than the entire record.
However, tdataset provides several methods to directly modify the entire record rather than individual fields. These methods include:
. Appendrecord is similar to append, but can assign values to fields without calling post;
. Insertrecord is similar to insert, but can assign values to fields without calling post;
. Setfields assigns values to the fields of the current record and must explicitly call post.
Each of the preceding three methods must pass an array of the tvarrec type as a parameter. Each element of the array corresponds to the value of a field. If the number of elements in the array is less than the number of fields in the dataset, the remaining field value is null.
For a dataset without an index, appendrecord adds a new record to the end of the dataset. For a dataset with an index, the new record is automatically moved to an appropriate location.
Setfields is used to assign values to the fields of the current record. Before calling setfields, you must call edit to bring the dataset to the dsedit state. After setfields is called, the post function must be called explicitly.
When setfields is called, if you only want to assign values to some fields and keep the values of other fields unchanged, you can use null or nil to assign values.
Assume that a dataset has five fields: name, capital, continent, area, and population. You can assign values to them as follows:
Countrytable. insertrecord (['Japan ', 'Tokyo', 'Asia ']);
The above program inserts a new record in the dataset and assigns values to the first three fields. Now you can assign values to the current record again. However, this time you only want to assign values to the Area Field and population field. The program will write the following:
With countrytable do
Begin
If locate ('name', 'Japan ', locaseinsensitive) then
Begin
Edit;
Setfields (nil, 344567,164 700000 );
Post;
End;
End;
Note: Nil instead of null is used here. Otherwise, the first three fields are set to null.
6.8 Cases
Tdataset events are mainly divided into two categories: Before series and after series. The list is as follows:
. Beforeopen and afteropen occur before and after opening a dataset;
. Beforeclose and afterclose occur before and after the dataset is closed;
. Beforeinsert and afterinsert occur before and after a new record is inserted;
. Beforeedit, Afteredit occurs before and after entering the dsedit state;
. Beforepost, afterpost occurs before and after the data set is written;
. Beforecancel and aftercancel occur before and after cancellation;
. Beforedelete and afterdelete occur before and after the deletion record.
In addition, when a new record is added to the dataset, the onnewrecord event is triggered. When the value of "calculated field" needs to be recalculated, The oncalcfields event is triggered.
Before series events are often used to abort operations. For example, when the delete function is called to delete the current record, the beforedelete event is triggered before the current record is deleted, you can call abort in the handle that handles the beforedelete event or trigger an exception to discard the current record. The program example is as follows:
Pocedure tform1.tablebeforedelete (Dataset: tdataset)
Begin
If messagedlg ('delete this record? ', Mtconfirmation, mbyesnocancel, 0) <> mryes then abort;
End;
After events are often used to notify users on the status bar. The program example is as follows:
Procedure tform1.table1afterdelete (Dataset: tdataset );
Begin
Statusbar1.simpletext: = format ('% d records exist', [dataset. recordcount]);
End;
The oncalcfields event is mainly used to give the value of "calculated field. The value of the autocalcfields attribute determines when an oncalcfields event will occur.
If the autocalcfields attribute is set to true, the oncalcfields event occurs in the following cases:
. When the dataset is opened;
. In the data control, the input focus is moved from one record to another record;
. In the data control, the input focus is moved from one field to another;
. The current record is modified or a record is retrieved from the database.
However, even if the autocalcfields attribute is set to false, the oncalcfields event is triggered when the value of any non-calculated field in the dataset changes.
Because oncalcfields events may occur frequently, the code for processing oncalcfields events should be as short as possible. When the autocalcfields attribute is set to true, the data of the dataset cannot be modified in the handle for processing the oncalcfields event, because once the current record is modified, the oncalcfields event is triggered again, resulting in an infinite loop. For example, if you call post in the handle for processing the oncalcfields event, the oncalcfields event is triggered, causing the post to be called again, and the oncalcfields event to be triggered again ......
6.9 tbdedataset
Tbdedataset is inherited from tdataset, which provides the ability to access data through BDE (borlanddatabase engine. This section mainly introduces tbdedataset. Readers should have a deep understanding of the tdataset introduced earlier.
Like tdataset, tbdedataset is also virtual and abstract. You do not need to use tbdedataset directly unless you want to create a custom dataset.
Tbdedataset reloads the methods that involve record navigation, indexing, and bookmarks in tdataset, and adds attributes, methods, and events that process BLOB fields and cache updates.
6.9.1 cacheblobs attributes
The cacheblobs attribute of tbdedataset is used to control whether BDE puts the Blob field content into the cache. If this attribute is set to true, when the application reads the Blob field value, BDE places the Blob field content in the cache, when the application reads the value of this field next time, it does not need to be retrieved from the database server, as long as it is retrieved directly from the memory, this improves the performance of applications.
However, if the application needs to update the Blob field value frequently, set the cacheblobs attribute to false to ensure that the retrieved blob field value is always the latest.
6.9.2 cache update
Tbdedataset provides the cache update technology. Cache update means that the application retrieves data from the database and creates a copy in the local cache. After the user modifies the data, it is only reflected in the cache, in the future, you can call applyupdates to reflect all the modifications to the dataset at a time.
It can be seen that the cache update technology can significantly improve the performance of applications and easily cancel modifications as long as applyupdates has not been called. Attributes, methods, and events related to cache update in tbdedataset are listed below:
. Cachedupdates if this attribute is set to true, the cache update is valid;
. Updateobject is used to specify a tupdatesql component to update a query-based dataset;
. Updatepending if there are pending records in the cache, this attribute returns true;
. Updaterecordtypes: Specifies which records in the dataset are visible;
. Updatestatus: returns the current update status;
. Onupdateerror: this event will be triggered if an error occurs during the update process;
. Onupdaterecord triggers this event every time a record is updated;
. Applyupdates writes the cached data to the dataset;
. Cancelupdates cancels pending changes in the cache;
. Commitupdates clears the cache; l fetchall Retrieves all records from the database to the cache;
. Revertrecord undo the modification to the current record.
6.10 tdbdataset
Tdbdataset is inherited from tbdedataset, which provides the ability to manage databases and sessions.
Several attributes and methods are added to tdbdataset to manage database and BDE session periods, including:
. Checkopen check whether the database has been opened;
. Database returns a tdatabase component;
. Dbhandle returns a BDE handle, which is used to call bde apis;
. Dblocale returns the current international language driver;
. Dbsession returns a BDE session object;
. Databasename is used to specify the database to be accessed;
. Sessionname is used to specify a BDE session object.
Here we will explain in detail the databasename and sessionname attributes. If the application needs to access a remote database server such as Sybase, Oracle, or Interbase, The tdatabase component should be used to connect to the database. In this case, the databasename attribute should be set to specify the database to be connected, it can be set to the name of the tdatabase component. If the tdatabase component is not explicitly used, set the databasename attribute to the BDE alias. For paradox and DBASE tables, it can be set as the table path.
The sessionname attribute is used to specify a BDE session object. If the application does not explicitly use the tsession component, you do not need to set this attribute. If the application explicitly uses multiple tsession components, you should set the sessionname attribute to specify one of them.
Generally, applications do not use attributes such as dbhandle, dblocale, and dbsession unless you need to directly call BDE APIs. These three attributes are read-only.
Tdbdataset also has a read-only provider attribute, which can return an iprovider interface. In multi-layer client/server applications, the client program needs to communicate with the application server through the iprovider interface.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.