Multi-layer database development 5: connecting to the database

Source: Internet
Author: User
Chapter 5 connecting to a database
The tdatabase component is useful in database applications. It can manage and manipulate database connections and control the continuity of database connections. The tdatabase component also provides the ability to manage transactions and apply for updating data.
Chapter 3 has detailed the relationship between tsession and tdatabase. All database connections are under the control of the tdatabase component, and all the tdatabase components are under the management of BDE session objects.
5.1 Permanent and Temporary tdatabase Components
In many cases, it is not necessary to explicitly use the tdatabase component. When an application attempts to open a database, a temporary tdatabase component is automatically created. Of course, this temporary tdatabase component is valid only during database connection. Once the database is closed, this temporary tdatabase component will be deleted.
However, in some database applications, especially client/server applications with two or more layers, it is best to explicitly use the tdatabase component. Any tdatabase component added to the form or data module during the design period is called the permanent tdatabase component, which is relative to the temporary tdatabase component.
The advantage of using the permanent tdatabase component is that you can establish a permanent connection and manage transactions. You can create BDE aliases dedicated to applications and respond to onlogin events.
The functions of the temporary tdatabase component are limited to some extent. Some of its key attributes are subject to the BDE Session object to which it belongs. For example, the keepconnections attribute of the BDE Session Object determines whether the database continues to be connected after all datasets are closed. The keepconnections attribute of the permanent tdatabase component is not affected by the keepconnections attribute of the BDE session object.
Sometimes, it is difficult to determine whether several tdatabase components need to be used, and you do not want to use temporary tdatabase components. At this time, you need to dynamically create tdatabase components at runtime.
To dynamically create a tdatabase component at runtime, declare a variable of the tdatabase type and call the create function of tdatabase to create an object instance of tdatabase. The program example is as follows:
Function runtimedbcreate (const databasename, sessionname: string): tdatabase;
VaR
Tempdatabase: tdatabase;
Begin
Tempdatabase: = nil;
Try
Sessions. opensession (sessionname );
With sessions do
Begin
With findsession (sessionname) Do
Result: = finddatabase (databasename );
If result = nil then
Begin
Tempdatabase: = tdatabase. Create (Self );
Tempdatabase. databasename: = databasename;
Tempdatabase. sessionname: = sessionname;
Tempdatabase. keepconnection: = true;
End;
Result: = opendatabase (databasename );
End;
Except
Tempdatabase. Free;
Raise;
End;
End;
You can call the runtimedbcreate function as follows:
VaR
Mydatabase: array [1 .. 10] of tdatabase;
Mydbcount: integer;
Begin
Mydbcount: = 1;
...
Mydatabase [mydbcount]: = runtimedbcreate ('mydb' + inttostr (mydbcount ),'');
INC (mydbcount );
...
End;
5.2 control system connection
Both permanent tdatabase components and temporary tdatabase components can control database connection behaviors through their attributes, methods, and events. This is also the main purpose of using tdatabase components.
5.2.1 specify a BDE Session Period
All tdatabase components must specify a BDE session to which it belongs. This requires two attributes: sessionname and session.
The sessionname attribute is used to specify the name of a BDE session. When a tdatabase component is put on a form or data module during the design period, its sessionname attribute is automatically set to "default", which is the name of the default BDE session period. If you have already placed several tsession components on the form or data module, you can select the value of the sessionname attribute from a drop-down list.
The session attribute is read-only and is used to return the BDE Session object to which the tdatabase component belongs. If the sessionname attribute is set to null or "default", the session attribute returns the default BDE session object.
After the BDE Session object is returned through the session attribute, you can access the attributes, methods, and events of the tsession, even if you do not know the actual name of the BDE session object.
5.2.2 specify the database to be accessed
To specify a database, you must use the aliasname attribute or drivername attribute. These two attributes are mutually exclusive. If one attribute is set, the other is cleared. Before modifying attributes such as aliasname, drivername, and databasename, you must set the connected attribute to false. Otherwise, an exception is triggered.
The aliasname attribute is used to specify the alias of a database. It can only be set to an existing BDE alias, such as dbdemos, defaultdb, and iblocal.
The database alias is generally defined by SQL explorer or BDE. However, you can also use the databasename attribute to define an application-specific alias. The databasename attribute can be set to an existing BDE alias. For paradox and DBASE tables, you can also set the path of the table.
The alias defined using the databasename attribute is only used in this application. It will appear in the drop-down list of the databasename attribute of the tTable, tquery, and tstoredproc component.
The drivername attribute is used to specify the type of a database driver. It can be set to standard (for dbase and paradox), MSSQL, Interbase, Oracle, Sybase, and Informix. After the drivername attribute is set, you must set the Params attribute to specify the connection parameter.
The database driver is actually a parameter of the BDE alias. Therefore, drivername is automatically cleared after the aliasname attribute is set. If the drivername attribute is set, the aliasname attribute is automatically cleared. Otherwise, there is a conflict. In this case, the drivername attribute does not seem to be useful, as long as the aliasname attribute is set. However, when the databasename attribute defines an application-specific alias, you need to set the drivername attribute to specify the driver used by the alias.
During the design period, you must specify a BDE alias or database driver or define a special alias. You can either use the object observer or double-click the tdatabase component to open the database Attribute Editor, then, set the value of the databasename attribute in the "name" box, set the value of the alias attribute in the "Alias Name" box, and set the value of the drivername attribute in the "Driver name" box.
You can also set the value of the databasename, aliasname, or drivername attribute at runtime, for example:
Database1.databasename: = edit1.text;
5.2.3 set BDE alias Parameters
Params attributes are required for parameters with BDE aliases, such as paths, server names, cache lengths, language drivers, user names, and passwords.
During the design period, there are three methods to set BDE alias parameters:
First, use SQL explorer or BDE administrator to define or modify aliases and parameters.
Second, click the ellipsis next to the Params attribute in the object observer to open the string List editor, and then type the parameter name and value in the format.
Third, double-click the tdatabase component to open the database Attribute Editor, as shown in Figure 5.1.
Figure 5.1 set BDE alias Parameters
Click defaults to list the default parameters corresponding to the driver in the parameter overrides box. for dbase and paradox, the default parameters are mainly paths, for remote servers, the default parameters are too many, including the server name, user name, password, and language driver.
Click the "clear" button to clear the "parameter overrides" box.
You can modify the parameters directly in the "parameter overrides" box or add new parameters.
To set the BDE alias parameters at runtime, The tstrings object is used. As shown in Figure 5.1, The Params attribute is actually a string list in the format of "name = value ". The program example is as follows:
With database1 do
Begin
Params. Clear;
Params. Add ('username = sysdba ');
Params. Add ('password = 100 ');
Loginprompt: = false;
Open;
End;
5.2.4 log on to the server
Most servers have strict security measures to prevent unauthorized access. The first level a user faces is logon, that is, entering the user name and password.
During the design period, when you try to connect to a remote server, Delphi 4 will launch a standard Logon dialog box that allows you to enter the user name and password.
You can log on to the Apsara stack console in three ways:
The first method is to set the loginprompt attribute to true. In this way, when you need to connect to a remote server, a standard Logon dialog box is automatically displayed, asking the user to enter the user name and password.
The second method is to set the loginprompt attribute to false and the Params attribute, which should contain the "user name" and "password" parameters, for example:
User name = sysdbapassword = masterkey
Note: the user name and password provided by the code in the program are easy to leak. We recommend that you do not use this method.
The third method is to set the loginparams parameter in the handle for processing the onlogin event. The program example is as follows:
Loginparams. Values ['user name']: = username;
Loginparams. Values ['Password']: = passwordsearch (username );
When you exit the handle for onlogin event processing, the value of the loginparams parameter is assigned to the Params attribute.
5.2.5 start to connect to the Database Server
To start connecting to the database server, you can call the OPEN function or set the connected attribute to true. In fact, setting the connected attribute to true will automatically call open. In this case, the onlogin event is triggered. If the program does not process the onlogin event, a standard Logon dialog box will pop up to allow users to log on.
If you try to open a dataset without connecting to the server, you will first call the OPEN function to connect to the server and automatically create a temporary tdatabase component as needed.
Once a connection is established with the server, the connection will remain as long as at least one dataset is active. If none of the datasets are active, whether the connection is disconnected depends on the value of the keepconnections attribute.
If the keepconnections attribute is set to true, the connection is maintained even if none of the datasets are active. For applications that frequently Open and Close datasets, you can avoid always logging on. If the keepconnections attribute is set to false, when all datasets are closed, the connection to the server is disconnected.
To disconnect a connection, you must call close or set the connected attribute to false. In fact, setting the connected attribute to false will automatically call close.
Close will automatically close all datasets and disconnect them. If you only want to disable all datasets but do not want to disconnect them, set the keepconnections attribute to true and then call the closedatasets function.
Note: even if the keepconnections attribute is set to true, the close function can always be called to disconnect.
5.2.6 network protocol and ODBC
Delphi 4 uses the BDE and SQL links drivers to connect to the database server. BDE can also drive ODBC to access a wider range of data sources.
Pay attention to the network protocol when configuring the SQL links and ODBC drivers. In most cases, the network protocol is configured by the client software of the database server, but for ODBC, you also need to configure the network protocol in a dedicated ODBC management program.
It is often difficult to connect to the server at the beginning. In this case, check whether the client software is correctly configured. If the TCP/IP protocol is used, check whether any software that supports TCP/IP is installed, such as Winsock. DLL, whether the server IP address is registered in the hosts file of the client, and whether the Domain Name Service is correctly configured.
5.3 traverse all data sets of a Database
The datasets attribute of the tdatabase component can be used together with the datasetcount attribute to traverse all datasets of a database.
The datasets attribute is an array. Each element of the datasets is an active dataset such as tTable, tquery, or tstoredproc. Each dataset can be accessed by serial numbers.
The datasetcount attribute returns the number of elements in the datasets array. The program example is as follows:
VaR
I: integer;
Begin
For I: = 0 to datasetcount-1 do
If datasets [I] Is tTable then
Datasets [I]. cachedupdates: = true;
End;
5.4 relationship between tdatabase and tsession
Tdatabase components are mainly used to manage database connections, while tsession is used to globally control the tdatabase components in an application, including temporary tdatabase components.
The tsession method is usually used for all tdatabase components, and does not take the status of the tdatabase component into account. For example, the dropconnections function of tsession closes all datasets and disconnects all databases, even if the keepconnections attribute of these tdatabase components is set to true.
Tdatabase can only manage the databases it connects to. For example, the closedatasets function of tdatabase only closes all datasets of a database, and does not close datasets of other databases.

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.