Delphi layer-3 Database Development and Application

Source: Internet
Author: User
Tags sql client
The server program is actually a COM project. It connects to the data source and
Client contact. This COM project must be registered on the server.

First, create a blank project.
File-> New-> Other-> Multitier-> Remote DaTa Module (Remote Data Module)
Dialog Box:
Coclass Name: Name of the COM program. The front-end searches for the COM program based on this Name.
(Project121)
Instancing: Execution Mode. Most instances use Multiple instances (Multiple instances)
Threading Model: thread mode. Apartment (unit) is recommended)

 

The following describes the options.

OK to generate a window in which data controls can be placed.

In Viwe-> Type Libray, we can see some features of this COM. We
You can also write down the GUID provided by the system for later use.
Add an ADOTable and set it to point to a database.
Set a DataSetProvider to point to ADOTable.

This completes the program design on the server side.
Save, compile, and register.

Here we need to make a few instructions:
1) on the client side, data controls are generally connected to Datasource, but on the server side, the master
To connect data to interfaces, use DataSetProvider as defined in Delphi 5.0 or later.
You do not need to perform the Export (Export) operation on each control, but
This simplifies the process and maintenance. However, each DataSet in the foreground must have
The corresponding DataSetProvider.
2) There are several options for creating COM:

A) Instancing:
Multiple Instance: an application can be called by Multiple foreground programs.
It is highly efficient to start and execute without consuming too many servers.
Resource and convenient management.
Single Instance: An application can only be called by one foreground program.
So when a query crashes
Other queries, however, a front-end call must be created on the server
Creates an application server's Process (Process), which occupies Resources
Many sources affect the overall server execution efficiency.
Internal: Create an In-Process COM Program (that is, the DLL file)
Because the Mult-Tier structure, the Application Server
Different from the front-end program, the two processes of the two machines
The same Process cannot be shared, so it is rarely set to Internal.
Mode.
B) Threading Model:
Apartment: each instance can process only one Request sent by the front-end at a time (please
If multiple In-Process COM programs are created at the same time
A com program will have a current process service, so the data is secure,
Of course, you must pay attention to conflicts between some shared variables.
Single: Single-threaded, cyclic operation, no multi-task issues.
Free: allows Remote DaThe ta Module handles multithreading issues by itself.
The user-End program must be processed in multiple threads.
Both: almost the same as Free, but the Callback of the corresponding front-end interface is connected
Continued.

If you cannot confirm whether the registration is successful after registration, you can use C: \ WINNT \ Regedit.exe to check.


In Two-Tier mode, the Client program is directly connected to the data source of the server,
In the Multi-Tier mode, multiple clients connect to an application server, because the charge is based on
The number of clients is calculated. Therefore, the database usage cost is relatively low.
The following example only provides the most basic functions for database operations.
Method.

1) create a common project.

2) place an TDCOMConnrction control on the Datasnap page. properties:
ComputerName: Server Name (automatically giving network neighbors)
ServerName: Application Server Registration Name (project121.Test121server)
If necessary, enter the GUID value for ServerGUID.
Connected = true is activated

NOTE: If debugging is performed on a Windows 2000 host, run
Project121.exe, and then you can find project121.Test121server in ServerName
Then, Connected = true is activated.

3) place a TClientDataSet Control (Ta Access page), properties:
Name: cdsCustomer (renamed again)
RemoteServer: DCOMConnrction1
ProviderName: DataSetProvider1 (the server will be activated)
Active: true (the connection will be normal after activation)

4) Place TDataSource. properties:
Dataset: Point to cdsCustomer.

The rest is like a common database design. Note that the TActionList control is used here, where
Write and exit at Standard ActIon cannot be found, you need to write it yourself:

Procedure TForm1.ApplyUpdateExecute (Sender: TObject );
Begin
CdsCustomer. ApplyUpdates (-1 );
ShowMessage ('has been correctly written to the database !! ');
End;

Procedure TForm1.CloseActionExecute (Sender: TObject );
Begin
Close;
End;

As long as the server is correctly registered, this program is used.

Section 4 SQL query on the client

Because the TQuery control does not exist on the client, it seems that the client server mode cannot be used for SQL
Query. However, Delphi solves this problem well. In fact, as long as the client is connected
The client's TClientDataSet contains a Provider
Corresponding to all the default properties and methods of the DataSetProvider on the server.
DataSetProvider has an Options attribute.
= True. Then, the poAllowCommandText of DataSetProvider can be accepted by the front-end.
And send it to TQuery.
It can be seen that the DataSetProvider interface is used to actually transmit data.
An interface is required to build a bridge for passing SQL statements.
The SQL query method on the client is as follows:

ClientDataSet. Close;
ClientDataSet. CommandText: = 'SQL statement ';
ClientDataSet. Open;

Section 5 Client query server alias set

Before SQL query, users often need to specify which database to query.
The BDE database Alias (Alias) on the server sets data to capture the foreground program
The specific method is:

First, create a TSession and a TDataBase on the server.

Session1 attributes:
SessionName = Session1_4

DataBase1 attributes:
DataBaseName: name of the database to be connected
SessionName: Session1_4 (SessionName value)

Added attributes for TQurey.
SessionName: Session1_4

In this way, you can use the Session object to manage the data source information.
To pass the value to the client

View-> Type Library display interface window.
Right-click ITest125Server (varies depending on the Set Name)-> New->
Create two methods:

GetDatabaseNames is used to pass the alias data. Its Interface Information is:
Return type: HRESULT
Parameters
Name type modifier

Param VARIANT * [out, retval]

SetDatabaseName, used to accept information from the client. The interface information must be passed in.
Information.

Return type: HRESULT
Parameters
Name type modifier

DBName BSTR [in] ---- alias uploaded
UserName BSTR [in]
Password BSTR [in]

After Refresh Implementation, two functions are generated.

Function TTest125Server. GetDatabaseNames: OleVariant;
Var
I: Integer;
DBNames: TStrings;
Begin
// Create a string array to store all database alias data of BDE.
DBNames: = TStringList. Create;
Try
// Use the Session control to obtain all database alias data of the current BDE.
Session1.GetDatabaseNames (DBNames );

/// Create a variable array and return the Result of the variable to the function.
Result: = VarArrayCreate ([0, DBNames. Count-1], varOleStr );

// Finally, specify the database alias data to the variable array.
For I: = 0 to DBNames. Count-1 do
Result [I]: = DBNames [I];
Finally
DBNames. Free;
End;
End;

In addition to getting the BDE database alias, the key of the above function also declares a variable number.
Group to store database alias data, so use the VarArrayCreate function to create an array of variables,
Parameter 1: Specify the array range.
Parameter 2: array data type. The data type must be
It must be set to varOleStr.

The second process is the online data provided by the client.

Procedure TTest125Server. SetDatabaseName (const DBName, UserName,
Password: WideString );
Begin
Try
// Input the database alias, name, and password from the front-end.
// Specify three data items to the TDatabase control and perform online operations.

Database1.Close;
Database1.AliasName: = DBName;
If (UserName <> '') and (Password <>'') then begin
Database1.Params. Values ['Password']: = PASSWORD;
Database1.Params. Values ['user name']: = UserName;
End;
Database1.Open;
Except
// If an error occurs online, an exception is thrown to the foreground program.
// The foreground program will use this exception to determine whether to input
// Activate the line data window.

On E: EDBEngineError do
Raise Exception. Create ('password required ');
End;
End;

Section 6 server-side customer count

In addition to the above functions, this program also adds an online user and queries user statistics
. Because the application execution mode is Multiple Instance execution mode
After a front-end is connected to IOT platform for the first time, the application server will activate the RemoteDataModule
Event program, and the OnDestroy event program, so you can use these two events
Calculate the number of users connected to the server. For the calculation of the number of queriesAfterOpen
Event function judgment.

-----------------------------------------------------------------
Form1, mainly used for display
-----------------------------------------------------------------

Procedure TMainForm. UpdateClientCount (Incr: Integer );
Begin
FClientCount: = FClientCount + Incr;
ClientCount. Caption: = IntToStr (FClientCount );
End;

Procedure TMainForm. IncQueryCount;
Begin
Inc (FQueryCount );
QueryCount. Caption: = IntToStr (FQueryCount );
End;
--------------------------------------------------------

COM Section

--------------------------------------------------------

Procedure TTest125Server. RemoteDataModuleCreate (Sender: TObject );
Begin
// Add a front-end plug-in (call the program on Form1)
MainForm. UpdateClientCount (1 );
End;

Procedure TTest125Server. RemoteDataModuleDestroy (Sender: TObject );
Begin
// Reduce the number of frontend clients (call the program on Form1)
MainForm. UpdateClientCount (-1 );
End;

Procedure TTest125Server. AdHocQueryAfterOpen (DataSet: TDataSet );
Begin
// Open a new TQuery query (call the program on Form1)
MainForm. IncQueryCount;
End;

For the complete Client/Server database instance, see SQL Server and SQL client
The data source must be adjusted by yourself.

Section 7 One-to-multiple-Table server programs

1. Application Server

A standard Form must be provided in advance.

File-> New-> Multitier-> Remote DaTa Module

CoClass Name: test63
Instacting: Multiple Instacting
Threading Model: Apartment

Add ADOTable1
ADOTable2
Datasouce1
DataSetProvider1 (in DaTa Access)
DataSetProvider2
Attribute:
ADOTable1 (master table)
ADOTable2 (slave table)
Connect a database with ConnectionString and TableName

ADOTable1 DataSetProvider1

 

Datasouce1

 

ADOTable2 DataSetProvider2


Connect to the corresponding database (here: the bonus database. mdb)
TADOQuery. SQL = select * from bonus
TADOQuery. Active = true

TDataSetProvider. Dataset = ADOQuery1

Save (Change project name to pChpServer), run (Register)

Client

DCOMConnection1
Property: ComputerName = computer name (not to be written locally)
ServerName = server-side program name (COM)
Connecter = true (indicating connected)

ClientDataSet1
Property: RemoteServer = DCOMConnection1
ProviderName = DataSetProvider1
Active-= true
ClientDataSet2
Property: RemoteServer = DCOMConnection2
ProviderName = DataSetProvider2
Active-= true

Add two TDataSource and connect the TDBGrid
ClientDataSet1 and
ClientDataSet2
It seems that the master-slave relationship should be displayed, but DBGrid2 does not.

Solution:
Double-click ClientDataSet1, And the Form1.ClientDataSet1 window appears. Right-click
Select "Add Field" on the menu, and the last line is displayed: ADOTable2.
It is very important to establish a master-slave connection.
OK to enter the Form1.ClientDataSet1 window (you can also adjust the display of the main table)
But ADOTable2 cannot be less, it actually uses the slave table as a field of the master table
Used ).
ClientDataSet2 attributes:
DataSetField = ClientDataSet1ADOTable2
Active = true
The master-slave relationship is established.

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.