Multi-level database development 8: Access table

xiaoxiao2021-03-06  103

Chapter 8 Visits Form This chapter describes how to use the TTable component in the database application. The top level of the TTable is TDBDataSet, and TDBDataSet is inherited from TBDedataset, and TBDedataset is inherited from TDataSet. Therefore, if you have completely mastered the content of Chapter 6, you should not feel unfamiliar with the TTable component.

8.1 General steps using a TTable component

The TTable component can access each row and each column in the database table. The TTable component can access the local database such as PARADOX, DBASE, Access, FoxPro, or access to the ODBC database, and access to remote databases such as Interbase, Sybase, and SQL Server.

You can also display all rows and all columns of the table, or you can select a range within a certain range, or retrieve one of the rows with filtering technology, you can search, copy, replace, or delete a table.

A TTable component often only accesss a form, but if needed, a TTable component can also access several forms.

8.1.1 Setting the TTAble component

Below is a general steps to use and set the TTable component, some applications may also need other steps.

The first step is to put a TTable member on the form or data module, set its Name property specifying the name of the component, and cannot be with the same name as other components in the same application.

The second step is to set the database to be accessed by setting the databaseName property.

The third step is to set the tablename property to specify the table to be accessed.

The fourth step is to put a TDataSource component on the form or data module and set its DataSet property to specify the TTable component.

The fifth step is to put a data control such as TDBGRID on the form and set its DataSource property to specify the TDataSource component.

Finally, set the Active property of the TTable component to True.

8.1.2 Specify the database to be accessed

DatabaseName properties are used to specify the database to be accessed. For PARADOX and DBASE, the DatabaseName property can be set to the BDE alias or table. For SQL databases, the DatabaseName property must be set to a BDE alias.

The advantage of specifying the database with a BDE alias is that you can access different databases as long as you modify the definition of an alias, and the application does not have to make any modifications. To modify the definition of an alias, use SQLExplorer.

Before modifying the DatabaseName property, you must set the Active property to false.

If you manage the connection with the database with the TDATABASE component, you can set the DatabaseName property as an app-specific alias.

8.1.3 Specify the table to access

The TABLENAME property is used to specify the table to be accessed. Before setting the tablename property, first set the Active property to false and set the databaseName property Specify the database to access.

You can specify the table to be accessed in the design period, or you can specify the table to be accessed at the runtime, and the program is as follows:

With OrderorCustTable DO

Begin

Active: = FALSE;

If TableName = 'Customer.db' Ten Tablename: = 'Orders.db'

ElsetAblename: = 'Customer.db';

Active: = True;

END;

8.1.4 Specified Type of Table

If the database to be accessed is PARADOX, DBASE, FOXPRO, or with a comma-separated ASCII text file, you must set the TABLETYPE attribute to specify the type of table.

By default, the TableType property is set to TTDEFAULT, and BDE will distinguish the type of form according to the file extension. The extension is .db, it is considered to be Paradox, the extension is considered to be DBASE, the extension is .txt, think is ASCII text, and no extension is considered to be Paradox. If you need to specify the type of the table, you must set the TableType property, set to TTDefault means that the TTDEFAULT is determined to determine the type of the table, set to TTPARADOX, set to TTDBase, is DBASE, set to TTFOXPRO, set is FoxPro, set to Ttascii is represented by ASCII text.

8.1.5 Open and close a table

To display and edit the data in the table, first turn on this form. To open a form, there are two ways, one, set the Active property to true, and then call the Open. After the form is opened, the data set enters the DSBROWSE state.

If you no longer need to display and edit the data in the table, or to modify some of the properties of the TTable component such as DatabaseName, TableName, and TableType, turn off the form at this time.

There are two ways to turn off the form. First, set the Active property to false, and the other is to call the Close function. After the form is closed, the data set will enter the DSINACTIVE state.

8.1.6 Control the reading and writing of the table

When a table is open, the application needs to obtain access to it and write, which is to use the three properties of the TTable component: CANMODIFY, READOONLY, and EXCLUSIVE.

CANMODIFY is a read-only property that can determine whether the table's data is modified by this property after a table is open. If the CANMODIFY property returns false, the application cannot modify the data of the table.

If the CANMODIFY property returns true, the application can modify the data of the table.

If the ReadOnly property is set to FALSE, the user can edit the data of the table. If you want to restrict the user can only view the data, you can't modify the data, you have to set the ReadOnly property to true.

The Exclusive property is used to set whether the application can exclusively form. If you want to exclusive access to the table, set the Exclusive property to True before opening the table, and other applications cannot read this form.

The Exclusive property is generally only available for local databases such as Paradox, DBASE, or FoxPro. For SQL databases, some servers do not support formal locks, although the server supports lock, other applications can still read the data of the table.

8.2 Search records in the table

To search in the table, there are several ways, we recommend calling the locate function and the lookup function, which can search for records based on any type field in any table, whether or not the table has established indexes.

The Locate function is used to search for a record that meets a specific condition in the table. If it is found, the record will become the current record.

The difference between the LOOKUP function and the locate function is that if the matching record is found, the current record is not changed. In fact, the Locate function and the Lookup function are not only available to the TTable component, which also applies to other data set components.

8.2.1 Search Based on Index

Record In addition to the Lookup function and the locate function, the TTable component also retains the GOTO series and the Find series, which can search the matching record based on the fields in the index, and make the recorded records as the current record. In Delphi 4, the fields in the index are called a key field.

Unlike LOCATE, gotoKey, Gotonearest requires that the index must have been established and can only be recorded based on key fields, and Locate does not have this request. The six methods in the GOTO series and the Find series are listed below: .editkey enables the dataset into the DSSetKey status, the program can specify the value of the key field.

.FindKey combines two methods for SetKey and GotoKey.

.Findnearest combines two methods for SetKey and Gotonearest.

.GotoKey searches for specific records based on the key field and makes the recorded records a current record.

.Gotonearest is similar to gotoKey, but as long as it is approximately matched (suitable for fields of string type).

.SetKey enables the dataset into the DSSetKey status, the program can specify the value of the key field. Unlike EditKey, if setkey is not called success, the original key value is cleared.

Among them, GotoKey and FindKey are functions that return to the Boolean value. If the call is successful, return TRUE and make the recorded records become current records. If you do not find a match record, these two functions returns false.

GotoneareStand and Findnearest are similar to GotoKey and FindKey, and different, if they do not find a frequently matched record, look for an approximate match record.

8.2.2 Goto Series

Use the GOTO family to search and locate records, usually such a few steps:

The first step is to set the indexName property Specify the index to use (for the SQL database, you need to set the indexfieldNames property). Of course, if you use the main index of the table itself, you can do not set this property.

The second step is to open the form.

The third step is to call SetKey to enable the data set into the DSsetKey state.

The fourth step is to specify the value of a key field via the Fields property or the FieldByname function.

The fifth step is to call GotoKey or GotoneARest lookup matched records.

The following example actually demonstrates the above five steps:

Procedure TsearchDemo.searchexactClick (Sender: TOBJECT);

Begin

Table1.setKey;

Table1.fields [0] .sstring: = Edit1.Text;

If not table1.gotokey the showMessage ('Record Not Found');

END;

The above example is given to gotoKey, in fact, Gotonearest is also almost, the program is now as follows:

Table1.setKey;

Table1.fields [0] .sstring: = 'SM';

Table1.gotonearest;

8.2.3 Find Series

The Find series method comes to search and positioning records, usually such a few steps:

The first step is to set the indexName property Specify the index to use (for the SQL database, you need to set the indexfieldNames property). Of course, if you use the main index of the form itself, you can not set this property.

The second step is to open the form.

The third step is to call the FindKey or Findnearest function to find the matching record. Both methods are to pass a keyValues ​​parameter to specify the value of the key field. Where Findnearest is only suitable for fields of string types.

8.2.4 KeyexClusive attributes and keyfieldcount properties

When you call Gotonearest, Findnearest, if the keyexclusive property is set to false, the matching record will become the current record (if you find); if the keyexclusive property is set to True, the next record of the matching record is current record. If there are multiple fields in an index, you just want to search for some fields, set the number of keyfield attributes to specify the number of keyfields. For example, assume that there are three key fields in the index, and you just want to search based on the first field to search, set the keyfield attribute to 1.

If the KeyFieldCount property is set to 2, it means a search based on the previous two fields. If the keyfieldcount property is set to 3, it means a search based on the previous three fields. However, if you want to search based on the first and third fields, KeyfieldCount properties are unable to force.

8.2.5 Search based on the deputy index

If you don't want to search based on the main index, you want to specify an index name through the indexName property based on the indexName property. Turn off the table before setting the indexName property. The program is now as follows:

Table1.close;

Table1.indexName: = 'cityindex';

Table1.open;

Table1.setKey;

Table1 ['City']: = Edit1.Text;

Table1.gotonearest;

For SQL tables, you can specify the fields in the index with the indexfieldNames property. For Paradox and DBase tables, indexes must be established in advance, and can only be searched based on fields in the index, otherwise it will trigger an exception.

Call the setKey or FindKey function each time, always clear the settings of the previous key value. If you want to continue searching based on the key value set in front, or add a new key field on the original basis, you cannot call setKey or FindKey to call the EditKey function. For example, suppose you set the CITY and Country two key values, now you have to add a Company field, and the program is as follows:

Table1.editKey;

Table1 ['Company]: = Edit2.Text;

Table1.gotonearest;

8.3 Sort by record

The role of the index is to sort records. By default, the Paradox table is arranged in an ascending order according to the main index. If you want to sort in other ways, you should use the secondary index (PARADOX or DBASE) or list the fields in the index (SQL).

8.3.1 Retrieving the defined index name

You can call the getIndexNames function to retrieve a table that is defined index name, which can return a list, which consists of all the names of all defined indexes. The program is now as follows:

Varindexlist: TLIST;

...

CustomersTable.GetIndexNames (IndexList);

Note: For Paradox, the main index is no name, so the list of the GetIndexNames function is not included in the list.

8.3.2 Which sub-index is specified?

For Paradox tables, if you want to sort by sub-index, first set the indexName property to specify a sub-index. E.g:

CustomersTable.indexName: = 'CustDescending';

If you are sorted by sub-index, you will be sorted by the main index, just set the indexName property to empty.

For DBASE tables, if you want to sort by sub-index, first set the indexfiles property to specify one or several index files. At the design period, you can click the omitial button on the edge of the indexfiles property in the object viewer to open the dialog box shown in Figure 8.1:

Figure 8.1 Setting indexfiles attributes during design

At the runtime, you can dynamically increase or delete the index file through the TStrings object, or you can use a string to list the name of the index file, and the file name is separated from the file name.

The following code specifies an index file animals.mdx, and specifying the NAME as a secondary index:

Animalstable.indexfiles: = 'animals.mdx';

AnimalStable.indexName: = 'name';

For SQL tables, the number of records of records depends on the order of the SQL statement. You can set the indexName property to specify an existing index, or set the indexfieldNames property directly specify the fields in the index, so that the SQL table is sorted by these fields.

The indexName property and the indexfieldnames property are mutually exclusive, set one of them, and the other is emptied.

The indexfieldnames property is a string list that can list all the names of the fields to be sorted, separated from each other. Can only be arranged in ascending order, as for if casement, it is sensitive, depending on the server.

The following code is trying to put the phonetable first pressing the lastname field and then press the firstname field to sort:

Phonetable.indexfieldNames: = 'lastname; firstname';

Note: If you use the indexfieldNames property to the Paradox and DBase tables, Delphi 4 will try to find no similar index, if not, trigger an exception.

8.3.3 Check the fields in the index

If you want to know a few fields in an index, which fields can be used, you can use the indexfieldcount property and the indexfields properties.

The indexfieldcount property can return the number of fields in the index. The IndexFields property is a string list consisting of the name of the field in the index. The program is now as follows:

VAR i: integer;

Listofindexfields: array [0 to 20} of string;

Begin

With CustomersTable Do

Begin

For i: = 0 to indexfieldcount - 1 do

Listofindexfields [i]: = indexfields [i];

END;

END;

8.4 Select some records

Databases are often huge, and an application usually only cares about some of the data. For TTable components, there are two ways to limit the records that the application can access. First, use filtration technology, it is not only suitable for TTable, but also for TQuery and TSToredProc. The second is to set the range, which is only available for the TTable component.

8.4.1 Differences for filtration and scope

Filtering and range is to select a part of the record, but their working methods are different.

The so-called scope refers to a period of continuous records, and the values ​​of these records are within a certain range. For example, suppose there is an employee form, pressing the lastname field, if the value of the LastName field is required in "Jones" and "Smith", you need to set the range. You can only set the range of the SQL table, you can set the range of fields that appear in the indexfieldNames property. Filtering does not need to rely on the index, similar to the SQL SELECT statement, just select a record that satisfies a particular condition, which is not necessarily continuous. For example, suppose there is an employee form that can be found in California, which is born in California and has a employee of more than 5 years.

From functional, filtering features are stronger than setting range. However, for a large database and records have been sorted in a field, selecting some of the records faster.

8.4.2 Starting point of setting range

To set the starting point of the range, you want to call SetRangeStart. SetRangeStart will enable the dataset into the DSsetKey status. Once setRangeStart is called, the assignment of the field will be the starting point for the field. For Paradox and DBase, you can only assign a value for the key fields after calling SetRangeStart.

For example, suppose there is a Customer table, sort based on the CustNo field. It can set the starting point and endpoint of the range:

WITH CUSTOMERS DO

Begin

SetRangeStart; FieldByname ('Custno'): = startVal.text;

Setrangend;

If endval.text <> '' THEN

FieldbyName ('Custno'): = endVal.text;

ApplyRange;

END;

The reader may notice that after calling setRangeend, first check if the user enters the end point of the user in edit box endVal, because if the range of end points are set to NULL, there will be no records selected.

If there are multiple fields in the index, you can assign all fields after calling SetRangeStart, or you can assign only part of the fields. If a field is not assigned, the value of this field is NULL. If you are assigning a field that is not the field in the index after calling SetRangeStart, it is invalid.

If you don't want to set the starting point of the range, just want to set the end point, you can not call SetRangeStart.

8.4.3 Terminal of setting the range

To set the end point of the range, call the SetRangend function. SetRanEnd will enable the dataset into the DSsetKey status. Once the setRangeEnd function is called, the assignment of the field will be the end point of the field. For Paradox and DBase, after calling the SetRangeEnd function, you can only assign a value for the key field.

Note: The starting point of the range can be omitted, but the end point cannot be omitted, even if the end is not critical. If the end point is not set, it will be considered that the end is NULL. At this time, no record is selected. The following example is based on the LastName field setting range:

With table1 do

Begin

SetRangestart;

FieldByname ('lastname'): = edit1.text;

Setrangend; FieldByName ('lastname'): = Edit2.Text;

ApplyRange;

END;

If there are multiple fields in the index, you can assign all fields after calling the setRangeEnd function, or only assigning a part of the fields. If a field is not assigned, the value of this field is NULL. If the pair is assigned to the fields in the index after calling setRangeend, it will trigger an exception. 8.4.4 Set the starting point and end point at the same time

In fact, it is not necessary to call SetRangeStart and SetRangend to set the starting point and end point of the range, as long as SetRange can set the starting point and end point at the same time. SetRange will enable the dataset into the DSsetKey status.

SetRange needs to pass two array types of parameters, one for setting the starting point, the other for setting the end point, the program is as follows:

SetRange ([Edit1.Text, Edit2.Text], [Edit3.Text, Edit4.Text]);

If there are multiple fields in the index, you can assign all fields when calling setRan, or only assigns a part of the field. If a field is not assigned, the value of this field is NULL. The assignment is invalid when invoing the fields in the index when calling setRange.

Note: When calling setRANGE, the starting point of the range can be omitted, but the endpoint cannot be omitted, even if the end is irrelevant. If you do not set the end point, it will consider the end of NULL. At this time, there will be no records selected.

8.4.5 Approximate Match

If the field that makes an index is a string type, you can give the approximation of the field when calling the setRANGESTART, SETRANGEEND, or SetRange function, and the program is as follows:

Table1.setRangeStart; table1 ['lastname']: = 'smith';

Table1.setRangend; table1 ['lastname']: = 'zzzzz';

Table1.ApplyRange;

The following code will enable the value of all the LastName fields greater than "SM" and the value of the firstname field is greater than the "J" record.

Table1.setRangeStart; table1 ['lastname']: = 'sm';

Table1 ['firstname']: = 'j';

Table1.setRangend; table1 ['lastname']: = 'zzzzz';

Table1.ApplyRange;

8.4.6 Application and Cancel Scope

Call SetRangeStart, SetRangend or SetRan only sets the starting point and end point of the range, but it has not really enabled the scope, but also needs to call the ApplyRange function.

After calling ApplyRan, the application can only work within a certain range of records. If you want to work in all records later, you can call CancelRange. However, after CancelRange, the starting point and end point of the original setting remains reserved because they may be used next time. The starting point and end point will always be retained unless the new starting point and end point are set.

8.4.7 Starting point and end point of the modification range

To modify the original starting point and end, you can call the EditRangeStart and EditRangeEnd functions. Calling EdiTRANGESTART and EDITRANGEEND will make the dataset in the DSSetKey state.

Once the EditRangeStart is called, the assignment of the field will be the starting point for the field. For PARADOX and DBASE, after calling EditRangeStart, you can only assign a value for key fields.

Once you call EditRangeend, the assignment of the field will be the end point of the field. For Paradox and DBASE, after calling EditRangend, you can only assign a value for the key field. 8.5 Operation of the overall table

The following describes a few operations of the overall form, including all records in the table, delete the table, replace the table, create a new table, and maintain synchronization between the two tables.

8.5.1 Delete all records in the table

To delete all records in the table, you can call the EMPTYTABLE function. For SQL tables, you must have permission to delete records. Recorded by EmptyTable deletion cannot be recovered.

Before calling EmptyTable, you must first set attributes such as DatabaseName, TableName, and TableType. If the table is opened, it must be opened in exclusive way. The program is now as follows:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

Begin

With table1 do

Begin

Active: = FALSE;

DatabaseName: = 'delphi_demos';

TableName: = 'Custinfo';

Tabletype: = TTPARADOX;

EmptyTable;

END;

END;

8.5.2 Delete a form

In the design period, you can delete a table, you can use the mouse to select the "delete table" command in the pop-up menu. Of course, there must be a DatabaseName property and a TABLENAME property in advance, and there will be a "delete table" command in the pop-up menu.

In the runtime, you want to delete a table, you can call DeleTable. Note: The table deleted with the deleteTable is unrecoverable. Before calling the deleteTable function, you must set the DatabaseName, TableName, and TableType properties, and the table must be in a closed state. The program is now as follows:

With table1 do

Begin

Active: = FALSE;

DatabaseName: = 'DBDEMOS'

TableName: = 'Customer';

Tabletype: = TTPARADOX;

Deletetable;

END;

8.5.3 Give a table

In the design period, you want to give a paradox or dbase table, you can use the mouse to select the "Rename Table" command in the pop-up menu.

In the runtime, you want to call a paradox or dbase table, you can call the RenameTable function, for example:

Customer.RenameTable ('Custinfo');

8.5.4 Creating a form

You can also create a table in the design period. You can create a table if you have SQL knowledge through the "CREATE TABLE" command (design period) or the CreateTable function (running period). However, it is necessary to be familiar with relevant properties, methods, and events of data set components, especially for TTABLE.

Below is a general step of creating a table:

The first step is to set the DatabaseName property Specify which database you want to put the form in.

The second step is to set the TABLETYPE attribute to specify the type of table. If it is paradox, dbase or ASCII text, set the TableType property to TTPARADOX, TTDBASE or TTASCII. If it is other type, set the TableType property to TTDEFAULT.

The third step is to set the name of the table in the table. If the TableType property is set to TTPARADOX or TTDBASE, you don't have to give an extension.

The fourth step is to establish a field definition. At the design period, you can click the omitted number button on the edge of the FieldDefs property in the object viewer, and Delphi 4 will open an editor as shown in Figure 8.2:

Figure 8.2 Building a field definition

Click the button on the toolbar to create a new field, click the button to delete a field, click the button to shift the order of the field, click the button to move the order in the field.

Select one of the fields to set the definition of the field (TFIELDEF object) in the object viewer.

At runtime, you can call the TFieldDefs's add function to create a field.

The fifth step is to establish an index definition (optional). At the design period, you can click the INDEXDEFS attribute edge in the object viewer, and Delphi 4 will open an editor as shown in Figure 8.3:

Figure 8.3 Establish an index definition

Click the button on the toolbar to create a new index, click the button to delete an index, click the button to shift the order of the index, click the button to move the index order.

Select one of the fields to set the definition of the index (TINDEXDEF object) in the object viewer.

At the runtime, you can call the TINDEXDEFS ADD function to create a new index.

Note: During the design period, you can define and index definitions and index definitions in an existing table. First set the DatabaseName property and the TableName property specify a existing table, then right-click on the TTable component, select the Update Table Definition command in the pop-up menu, this command will make the fields in this table define and index Define reads the fielddefs attribute and indexdefs properties. Next, set the DatabaseName property and the TableName property according to the first step and the second step.

The sixth step is to create this form. At the design period, you can use the mouse to select the "CREATE TABLE" command in the pop-up menu. At the runtime, you can call the CreateTable function.

Note: If the new table is reinable with an existing table, the existing form will be overwritten and cannot be recovered.

The following code demonstrates how to create a table dynamically at the runtime:

VAR

NEWTABLE: TTABLE;

NewIndexOptions: TINDEXOPTIONS;

Tablefound: boolean;

Begin

NEWTABLE: = TTABLE.CREATE;

NewIndexOptions: = [ixprimary, ixunique];

WITH NewTable DO

Begin

Active: = FALSE;

DatabaseName: = 'DBDEMOS'

TABLENAME: = Edit1.Text;

TableType: = TTDEFAULT;

Fielddefs.clear;

Fielddefs.Add (Edit2.Text, ftinteger, 0, false);

Fielddefs.add (Edit3.Text, ftinteger, 0, false);

Indexdefs.clear;

Indexdefs.Add ('PrimaryIndex? Edit2.Text, NewIndexOptions);

END;

TableFound: = FindTable (Edit1.Text);

If Tablefound = True Then

IF messageDLG ('Overwrite EXISTING TABLE', MTCONFIRMATION, MBYESNO, 0) = MRYES TENTABLEFOUND: = FALSE

IF not Tablefound Then

CreateTable;

END;

8.5.5 Keep synchronization between two tables

Multiple TTable members can point to the same table, that is, their DatabaseName properties, and Tablename properties. The TDataSource components connected to each TTable component can be different, that is, they can operate independently, in different TTable components, the current recorded position is different. For example, in Table1, the 2nd record is the current record, and in Table 2, the third record is the current record.

However, you can call the Gotocurrent function to keep multiple TTable components to synchronize. For example, Article 2 of CustomertableOne is the current record, and in CustomertableTwo, Article 3 record is the current record. Can call Gotocurrent like this:

CustomertableOgotocurrent (CustomertableTwo);

If the two TTable components to synchronize are not in the same data module or in the form, you can write:

CustomertableOgotocurrent (Form2.customertabletwo);

8.6 Master / Detail Relationship

The MASTERSOURCE attribute of the TTable component and the masterfields property can be used to create a pair of master / detail relationships.

Both attributes can be used in the detail table. Where the MASTERSOURCE property is used to specify a TDataSource component that specifies the Master table for the DataSet property of the component.

The Masterfields property is used to specify one or more fields that are used to connect the Master table and the Detail table. If there are multiple fields, the semicolons are separated from each other, for example:

Table1.masterfields: = 'orderno; itemno';

Below us, we will explain the general steps to establish Master / Detail relationships. Suppose the Master table is called CustomersTable, the Detail table is called Orderstable.

In the first step, put the two TTable members and two TDataSource components on the form.

In the second step, set the DatabaseName property of the first TTable component to DBDemos, set the TABLENAME property to Customer, and set the Name property to CustomersTable.

In the third step, set the DatabaseName property of the second TTable component to DBDemos, set the TABLENAME attribute to Orders, and set the Name property to Orderstable.

In the fourth step, set the Name property of the first TDataSource component to CustSource and set the DataSet property to CustomerStable.

In the fifth step, set the Name property of the second TDataSource component to ORDERSSOURCE, set the DataSet property to OrderStable.

In the sixth step, put the two TDBGRID members on the form and set the DataSource attribute of the first TDBGRID component to CustSource, and set the DataSource property of the second TDBGRID component to OrdersSource.

Step 7, set the ORDERSTABLE's MASTERSOURCE attribute to CustSource, which connects the Customer Table with the Orders table. In the eighth step, click the ORDERSTABLE's MASTERFIELDS attribute to open the "FieldLink Designer" dialog box, select Custno in the "Available Indexes" box, then select Custno in the "Detailfields" box and "Master Fields" box, single Click the "Add" button.

In the ninth step, set the CustomersTable and OrderStable Active attribute to True.

Step 10, compile and run this procedure. You will find that when you browse the Customer table in the first grid, the ORDERS table in the second grid will display all orders of the current customer.

8.7 Nested Table

Delphi 4 uses the TNESTEDTable component to access the data in the nested table, and TnestedTable is inherited from TBDedataSet. Here is the general steps to access the nested table:

In the first step, put a data set component such as TTABLE, TQUERY in the form or data module, which must contain a field of TDataSetField or TreferenceField type.

In the second step, put a TnestedTable member on the form or data module, set its DataSetField property to specify the field to access the TDataSetField or Treference field, you can choose from the drop-down list.

In the third step, put a TDataSource component in the form or data module, set its DataSet property to specify the TnestedTable component.

In the fourth step, put a data control such as a TDBGRID component on the form or data module, set its DataSource property to specify the TDataSource component.

Step 5, set the Active property of the TnestedTable component to True in the design period or run.

8.8 Introducing data from another table

The BatchMove function of the TTable component can introduce data from other tables, including copying, adding, modifying, or deleting records, and returns the number of recorded records.

The BatchMove function needs to pass two parameters, one is the name of the source dataset, and the other is an operation mode. The BatchMove function supports the following ways:

.batappend Distributes all records in the source table to the end of the target table;

.batupdate uses records in the record update target table in the source table;

.batappendUPDate adds the record in the source table to the end of the target table;

.batDelete Delete the source table repeated record in the target table;

.batcopy copies the source table to the target table.

The following code updates the record in the current table with records in the Customer table:

Table1.batchmove ('Customer.db', Batupdate);

The BatchMove function is relatively simple compared to the TBATCHMOVE components. If you want to move a lot of records, it is best to use the TBATCHMOVE component.

8.9 Using TBATCHMOVE

The TBATCHMove component encapsulates a part of the BDE capabilities to introduce data from another data set. The TBATCHMove component is often used to download data from the server or load local data to the server.

The TBATCHMove component automatically creates a new table and maps the field names and types in the source data set.

8.9.1 General steps using the TBATCHMOVE components

The first step is placed on the form or data module as the source data set on the form or data module.

In the second step, put another TTable member on the form or data module as the target data set.

In the third step, put a TBATCHMOVE component on the data module, set its source attribute to specify the source dataset, set its Destination property to specify the target dataset. In the fourth step, set the mode attribute to specify the mode of operation, which can be set to BataPpend, Batupdate, BatappendUpdate, Batcopy, BatDelete, etc.

The fifth step (optional), set the probleMTableName property Specify the name of a table, and there is a problem with a problem when performing batch movements will be placed in this table. Set the keyvioltablename property Specify a name of a table, updating a paRadox list, when you violate the main index definition, will put it in this table. Set the ChangeDTableName property Specify the name of a table, and perform a record in the target table when performing a batch mobile operation, will be placed in this table.

The sixth step (optional), set the mapping mode of the mappings property specified by the field.

Step 7, calling Execute to perform bulk movements.

8.9.2 Specify how to operate

The Mode property of the TBATCHMOVE component is used to specify how to operate:

.batappend Distributes all records in the source table to the end of the target table;

.batupdate uses records in the record update target table in the source table;

.batappendUPDate adds the record in the source table to the end of the target table;

.batDelete Delete the source table repeated record in the target table;

.batcopy copies the source table to the target table.

For BataPpend mode, the target data set must be existing. If desired, BDE will automatically perform conversion of data types, but conversions are not always successful. For BatupDate mode, the target dataset must be existing and an index must be established. The TBATCHMOVE component updates the recorded records in the target data set according to the records in the source data set. During the update, BDE will convert data types as much as possible.

For BatAppendupDate, the target data set must be existing and an index must be established. The TBATCHMOVE component updates the recorded records in the target data set according to the records in the source data set. If the matching record is not found, the TBATCHMove component adds the record at the end of the source data set.

For BATCopy, the target dataset is preferably not existing. If there is already existing, the record in the target data set will be overwritten by the records in the source data set. If the structure of the source data set and the target dataset is different, for example, one is Paradox, the other is InterBase, and BDE will convert as much as possible. However, the TBATCHMOVE component does not copy the index of the source data set, error correction rules, and stored procedures.

For BATDELETE mode, the target data set must be existing and an index must be established. The TBATCHMOVE component deletes the duplicate record in the target dataset according to the key field.

8.9.3 Mapping field type

By default, when the source data set and the target dataset are batch, it is matched in the field position, that is, the first field in the source data set is still the first field in the target data set, analogy. If you do not want to match the location of the field, you want to match the name of the field to set the mappings property.

The mappings attribute is a list of strings. Assume that there is a field called SourceColname in the source data set, I hope it matches the destColName field in the target dataset, and this page should be added in the mapping property:

Destcolname = SourceColname

The program is now as follows:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

Var Maps: tstringlist;

Beginwith Maps DO

Begin

CLEAR; Add ('Custno = Customernum');

Add ('ssn');

END;

Batchmove1.mappings: = MAPS;

END;

If the data type of the fields on both sides are different, Delphi 4 will convert as much as possible, but data or accuracy may be lost. Suppose a field is char (10), if attempting to convert to Char (5), the last 5 characters will be cut off.

8.9.4 Performing a batch movement

Call the Execute function will perform a batch movement. For example, suppose BATCHMOVEADD is the name of the TBATCHMove component, to perform a batch movement, you can write:

BatchMoveAdd.execute;

In fact, the batch movement can be performed at the design period, and the method is: Right click on the TBATCHMove component and select the "Execute" command in the pop-up menu.

After calling Execute, you can access the MovedCount property and see how many records that actually move.

The RecordCount property is used to limit the number of records per batch move. If the RecordCount property is set to 0, there is no limit.

8.9.5 Handling error

In the process of batch moving operations, two types of errors may occur, one is the data type conversion error, and there is a violation of data integrity.

If the AbortonProblem property is set to TRUE, you will stop batch movements as long as you encounter a data type conversion error. If the AbortonProblem property is set to false, even if you encounter a data type conversion error, you will not stop batch movement operations. These erroneous records can be found in the table specified by the probleMtableName property.

The problemcount property returns the number of records with errors. If the AbortonProblem property is set to true, the problemMcount property returns up to 1, because once an error is encountered, the operation stops.

The AbortonkeyViol property is similar to the AbortonProblem property. If the Abortonkeyviol property is set to TRUE, you will stop batch movements as long as you encounter a violation of data integrity.

You can set the ChangeDTableName property to specify a name of a table, let the TbatchMove component written in this table in the TBATCHMove component.

You can set the name of the keyvioltablename property to specify a table that allows the TBATCHMove component to put all the records of violations of data in this table.

You can set the probleMTableName property to specify a name of a table, allowing the TbatchMove component to write all data type conversion errors to this table.

转载请注明原文地址:https://www.9cbs.com/read-95941.html

New Post(0)