Chapter 2 Single-layer and two-story application single-layer and two-story database applications are relatively simple, applications and databases are often on the same file system, even on the same disk. Both types of database applications are less suitable for accessing the same database at the same time in multi-user environments.
For single-layer applications, Delphi 4 provides two ways of obtaining data, one way is through BDE, and another way is by file. The two layers of applications generally use BDE.
2.1 BDE-based applications
Since the BDE and the data access component are processed, such as reading data, update data, record navigation, etc., writing a two-story application with almost no difference between writing a single-layer BDE-based application.
When you release BDE-based applications, BDE must be released at the same time, which will make the number of bytes of the application increase, and also increase the release, installation difficulty. But no matter what, BDE's role is still unsubstituted.
2.1.1 Architecture based on BDE
A BDE-based single or two-layer application is usually composed of such several parts:
The user interface, its main components are data controls;
One or several data set components for introducing data from the database;
One or a few TDataSource components for connecting data sets and data controls;
One or several TDATABASE components (optional) for controlling transactions. In two layers of applications, the TDATABASE component can also manage the persistence of database connections and do not log in;
One or several TSESSION components (optional), manage the connection of the database in a multi-threaded application.
Figure 2.1 demonstrates the architecture of BDE-based applications: Figure 2.1 BDE-based architecture.
2.1.2 Understanding Database and Data Set
Database and datasets are two concepts that have both connection and difference. The database includes both data in the table, and also contains properties, indexes, and stored procedures of the table itself. The data set is mainly used to introduce data in the table. A BDE-based application has at least one data set component.
Each BDE-based data set component has an open property called DatabaseName, which is used to specify the database to be accessed.
The DatabaseName property can be set to the BDE alias of the database. An individual name not only represents the database, but also represents the configuration information of the database. Different types of databases such as Oracle, Sybase, Interbase, Paradox, DBASE, their configuration information is also different. Use BDE Administration or SQL Explorer to create and manage BDE alias.
For the Paradox or DBase database, the DatabaseName property can also be set to the directory where the table is located. If the application explicitly uses the TDatabase component to connect to the database, the DatabaseName property can be set as an app-specific alias.
2.1.3 Using the session period object
The session period object (TSESSION) manages the connection to the database in multi-threaded database applications. The role of the session period is mainly reflected in four aspects.
Manage BDE alias. You can create a new alias with the session period, delete an alias, and modify the parameters of the alias. By default, the alias for creating and modifying the session period object is only valid. However, you can call Tsession SaveConfigFile to permanently save the alias into the BDE configuration file, so that other session periods and other applications These alias can be used.
Control the connection of the database in two sets of database applications. If the Tsession's KeepConnections property is set to True, even if there is no data set in the active state, it maintains the connection to the database, although it is astonished, but you can avoid the next connection database. Provide Paradox and DBase in a single layer of database application. You can display both a dialog to allow the user to enter a password or provide a password in the program. If you plan to smoothly transition to two or multi-layer architectures, you must design a manual interface to allow users to enter usernames and passwords, even if they are currently not used in single-layer database applications. Specifies the BDE network control file PDoxusrs.net and the directory of private files.
If the application needs to access the same database in a few locations, you must use multiple session period objects to manage the connection connection. If there is no such thing, it is likely to cause unexpected consequences.
2.1.4 Connecting Database
The BDE contains different types of drivers for connecting different types of databases. The STANDARD version of Delphi4 contains drivers to access local databases such as Paradox, DBASE, FoxPro, and Access. In addition to the drivers accessed by the local database, Delphi 4, the Professional version of the Delphi 4 also includes an ODBC driver that accesses a wider range of data sources through the ODBC driver. The CLIENT / Server version of Delphi4 and Enterprise also contains SQL Links that can access remote large databases, including Interbase, Oracle, Sybase, Informix, Microsoft SQL Server, and DB2.
2.2
A transaction is actually a set of action, which must be successfully performed before the table is submitted. If there is an action execution failed, all the actions will be undo (undo) so that there will be no inconsistent data in the database.
By default, BDE provides an implicit transaction power, when a record of the dataset is written in the database, BDE can guarantee that there is no part of the field to be updated and the other part of the field is not updated.
In the case of a multi-user environment, it is best to explicitly use transactions, because the implicit transaction power is limited, it will cause network overhead to increase, the application performance is lowered.
2.2.1 Explicitly use transactions
In BDE-based database applications, there are two ways to explicitly use transactions, and these two methods are mutually exclusive and cannot be used at the same time.
Connect the database through the TDatabase component, then control the transaction through attributes and methods such as TDatabase STARTTRANSACTION, COMMIT, ROLLBACK, INTRANSACTION, and TRANSISITION. The advantage of this way is that there is no need to rely on a specific database or server, and the programs have better transplantation, no extra code.
Using the so-called "passthrough SQL", the SQL statement is passed directly to the remote SQL server or an ODBC server via the TQUERY component. The advantage of this way is that the transaction management capabilities of the server can be directly used, but this is related to a specific server, the transplantability of the program is difficult to guarantee.
Single-layer applications cannot use the "PASSTHROUGH SQL" mode to control transactions with TDATABASE components. The two layers of applications can use the TDATABASE components or use the "PassthRough SQL" mode.
2.2.2 How to control a TDATABASE component
The first thing to call StartTransaction start a transaction. Once a transaction is activated, all read and write operations are related to transactions unless explicitly terminated. You can access TDatabase of the Intractions property, if this property returns true, indicating that a transaction has now begun. At this point, you want to retrieve data in the database depends on the transaction isolation level (Transiration property). After starting a transaction, you can read and write the database, in order to keep the modified data permanently saved to the database, TDATABASE should be called to submit. Commit is usually called in the try part of the Try ... Except structure, so that if the commit is not called success, there is a chance to call Rollback. The program is now as follows:
Database1.startTransaction;
Try
Table1.edit;
Table1.fieldbyName ('Custno'). Asinteger: = 100;
Table1.post; database1.commit;
EXCEPTION
Database1.rollback;
END;
2.2.3 Transisault Attribute
If there are multiple transactions in processing, and accessed the same table, how these transactions are interacting with each other, which is determined by the transaction isolation level set by the TransisLation property.
If this property is set to TidiRTYREAD, it is allowed to read other transactions to have a modification that has not been submitted for the database. The unsubmitted modifications may be rolled back at any time, so the data read in this case is unreliable.
If this property is set to TireAdCommitted, you are allowed to read other transactions to modify the database. If this property is set to TirePeatableRead, you are not allowed to read other transactions to modify the database. Different servers support different transaction isolation levels, if the transaction isolation level set by the Transisault property is not supported by the server, BDE will automatically reduce the transaction isolation level.
Note: When using a transaction to PARADOX, DBASE, Access, and FoxPro, you should set the TRANSILATION property to TidiRTYREAD instead of default TireAdCommitted, otherwise, BDE will report an error.
2.2.4 Passthrough SQL
The so-called "passthrough sql" is passed directly to the remote server via TQuery, TSTOREDPROC or TUPDATESQL component, which contains calls to the server transaction function.
To use "PASSTHROUGH SQL", you must meet a few conditions: must be a Client / Server version, and the SQL Links driver is installed. A network protocol is correctly configured. Access to the remote server. You must set the "SQLPASSTHRU MODE" parameter to "Not Shared" with SQL EXPLORER.
2.2.5 Local Transactions
For local databases such as Paradox, DBASE, Access, and FoxPro, BDE also provides transaction power, referred to as local transactions.
From a programming perspective, local transactions are not two of transactions with remote databases. However, its function is limited:
No crash self-recovery
Data definition statement is not supported.
It is not possible to perform a transaction for a temporary table.
For Paradox Table, an index must be established. Otherwise, the data cannot roll back.
The number of records that can be locked and modified is limited, and Paradox is limited to 255 records, and DBASE is limited to 100 records.
For the ASCII text file, you cannot perform a transaction.
The transaction isolation level (Transisault property) can only be set to TidiRTYREAD. 2.2.6 Cache Update
BDE provides a cache update technology. The process of cache updates is such that the application retrieves data from the database, modify the data, in fact, in the local cache, will be applied to update the data set in the cache.
Obviously, the cache update technology can improve efficiency and reduce the amount of transmission on the network. However, caching updates are still different from transactions. The data in the cache is only visible to this application. Before the application update, other applications can't know which modifications do these data do. So, for those frequently modified data do not apply cache update technology, because A users may change data to 10, and B users change data to 20, C users change data to 30, they are fully possible to simultaneously travel to the database Apply for updates, this will cause conflicts.
It is based on the above reasons, and the data set components have a cachedupdates property that allows you to choose to use a cache update technology.
2.2.7 Creating and Reconstructing Forms
In BDE-based applications, you can dynamically create a table with a TTable component, or create an index in a existing table.
To create a table, first create a field definition (FieldDefs property), then create an index definition (indexdefs attribute), and finally call CreateTable. You can also right-click the TTable component in the design period, select the "CREATE TABLE" command in the pop-up menu.
Note: If you want to create an Oracle8 type table, Delphi 4 does not create the ADT field, array field, reference field, and dataset field.
The structure of the table can also be changed during the running period (this is referred to as reconstruction), which requires calling a API called DBIDORESTRUCTURE. However, if you just have an index, call AddIndex.
In the design period, you can create and reconstruct the ParaDox and DBase table using Database Desktop, using SQL Explorer to create and reconstruct the SQL form.
2.3 File-based single-layer database application
File-based single-layer database applications are used to use the TclientDataSet component. The TclientDataSet component can access data from the file, establish a copy of the data in the memory, so that the access and operation of the data is very fast, but the capacity of the data is limited by memory.
2.3.1 TclientDataSet
TclientDataSet does not need to rely on BDE, which means that the application does not have to overhead memory for BDE, but the data itself needs memory. TclientDataSet only requires support for dynamic link library dbclient.dll, so the programs created with TclientDataSet are relatively simple, save the BDE configuration and maintenance.
It is because TclientDataSet does not use BDE, so file-based single-layer database applications do not apply to multi-user environments. Although TclientDataSet does not support BDE, since TClientDataSet is inherited from TDataSet, most of them can perform operations to TTABLETSET components, including data, including TclientDataSet, which can display TclientDataSet with standard data controls. You don't have to use the TDatabase component, because there is no database that needs to be managed, it is not necessary to support transactions. It is also not necessary to use the TSession component unless the application is multithreaded.
BDE-based database applications and file-based database applications are different from how to create data sets and access data.
2.3.2 Creating a Data Set in Design Period
Since the file-based single-layer database application is not a ready-made database, its primary task is to create a data set. Once you have created a dataset, you can save it to the file, you can take it out from the file without having to rebuild the data set. However, when saving the data set, the index will not be saved together, so each time you read the data set from the file, you have to re-establish the index. You can create a data set in the design period field editor, and the general steps are:
Place a TclientDataSet component on the form, right click, select the "Fields Editor" command in the pop-up menu, and Delphi 4 will open the field editor, as shown in Figure 2.2.
Figure 2.2 Field Editor
Right click on the field editor, select "New Field" command in the pop-up menu, Delphi 4 will open the "New Field" dialog, as shown in Figure 2.3
Type a field name in the "name" box, select the data type of the field in the "Type" box, set the field length in the "Size" box, "Component" box will automatically generate the object name of the field.
The "Field Type" box is used to specify the generated type of new field (not the data type of the field), you can choose "Data", "Calculate", "Lookup", "INTERNALCALC" and "Aggregate".
The field created with the field editor is called a permanent field. After creating a permanent field, right-click the TclientDataSet component, select the "CREATE DATASET" command in the pop-up menu. At this point, Delphi 4 will create an empty dataset without records. Right-click the TclientDataSet component again, select the "Save to File" command in the pop-up menu, save the data set to the file, the extension is .cds.
2.3.3 Creating Data Sets at runtime
To create a TClientDataSet-based data set, first create a field definition and index definition, this is similar to that created a TTable component-based data set, and the TclientDataSet does not have DatabaseName, TableName or TableType, because TclientDataSet is not Need to access the database directly.
Establish an index to use the indexdefs property, this property is a TINDEXDEF object. It has two properties to explain here: First, the descfields property, the other is the CaseinsFields property.
If the TINDEXDEF's Options property contains the ixdescending element, record the descending order of all fields. If you want to make records in ascending order according to some fields, use the descfields attribute to use the descfields attributes according to the descending order of the other field. Suppose a data set has three fields, called Field1, Field2, and Field3, if the descfields property is set to "Field1; Field3", indicating that the field of field2 is arranged, pressing the descending order of Field1 and Field3.
The role of the CaseinsFields property is similar to the DESCFIELDS attribute, and details are not described here.
After establishing a field definition and index definition, call CREATEDATASET, and the program is as follows:
Procedure TFORM1.FormCreate (Sender: TOBJECT);
Begin
With clientdataset1 do
Begin
{Define a field called Field1}
With Fielddefs.AddfieldDef Do
Begin
DataType: = ftinteger; Name: = 'Field1';
END;
{Define a field called Field2}
With Fielddefs.AddfieldDef Do
Begindataratype: = ftstring;
SIZE: = 10;
Name: = 'Field2';
END;
{Define an index called intIndex}
With indexdefs.addIndexdef do
Begin
Fields: = 'Field1';
Name: = 'intIndex';
END;
CreateDataSet;
END;
END;
2.3.4 Creating Data Sets Based on an existing form
If you want to convert a BDE-based application to a single layer-based application, you must first convert an existing table to the format that the TclientDataSet can identify, the operation steps are:
Add a TclientDataSet component to the form, click the right mouse button, select the "Assign local" command in the pop-up menu, pop up a dialog, let you introduce data from the local BDE-based data set, as shown in Figure 2.4 Indicated.
Select a local data set and click the OK button.
Right click on the TclientDataSet component again, select the "Save Tofile" command in the pop-up menu.
2.3.5 Access data in a file
In a single-layer file-based application, TclientDataSet automatically maintains a record of a data change. If you are not prepared to restore the original data, you can call MergeChangelog to combine changes in the data.
However, even if the changes are incorporated into the data, the data is still in memory, and the data will be lost when the application is turned off. Therefore, you must also call SaveTofile to save the data to the file.
SaveTofile only saves the structure and data of the dataset, but does not save the index. Therefore, you must rebuild the index every time you open the data set.
To open the data set saved by SaveTofile, you can call LoadFromFile.
If each open and saved files are constant, you can also set the filename properties of the TclientDataSet. When the TclientDataSet's Active property is set to TRUE, data is automatically read from the specified file. When the TclientDataSet's Active property is set to FALSE, the data will be saved to the specified file.
2.3.6 briefcase mode
For those who often travel on the road, they often get some data from the database before departure. After coming back, it is necessary to write the modified data back to the database, which is the so-called "briefcase" mode.
In applications of multilayer architecture, TclientDataSet is generally acquired from the application server via the iProvider interface. To work according to the "briefcase" mode, you must access data in the file.
The key to the "briefcase" mode is to save the data to the file, so the user interface user interface should allow the user to retrieve data from the application server and save it to the file, allow the user to adjust the data from the file and update the database, and TclientDataSet LoadFromFile and SavetOfile fully implement these features.
Another key to the "briefcase" mode is that the client must be able to determine if the application server is currently connected, in other words, even if it is offline, the client program must work.
2.3.7 Smooth transition to three-layer architecture
In the two-layer architecture, one layer is a database server and the other is an application. The application is logically divided into two major parts, one is the user interface, the other is the data access link. To smoke a two-story Client / Server application, transition to the three-layer Client / Server application, generally taken such a few steps. The first step is to create a new item as the application server and put the data access link portion on the application server. Add the TDataSetProvider or TPROVIDER component to the application server, there is a dataset, add a TDataSetProvider or TPROVIDER component.
The second step is to modify the existing two-layer architecture, remove the part involving the data access link, so that this program only remains the user interface portion.
The third step is to replace the original data set component with the TclientDataSet component, then join one or several MIDAS connection members such as TDCOMConnection.