Chapter 5 Connecting Databases in Database Applications, TDATABASE components are useful. It can manage and manipulate the connection of the database, control the persistence of database connections. The TDATABASE component also provides functions for managing transactions and application update data.
The third chapter has detailed the relationship between Tsession and TDatabase, all database connections under the control of the TDatabase component, and all TDatabase components are under the management of the BDE session object.
5.1 Permanent and temporary TDATABASE components
In many cases, it is not necessary to explicitly use the TDATABASE component. A temporary TDATABASE component is automatically created when an application is trying to open a database. Of course, this temporary TDATABASE component is only valid during the database connection. Once the database is turned off, this temporary TDATABASE component will be deleted.
However, in some database applications, especially in two or multi-layer Client / Server applications, it is best to explicitly use the TDATABASE component. Any TDATABASE component we add to the form or data module is weighted in the design period, we are called a permanent TDATABASE component, which is relatively temporarily TDATABASE components.
The advantage of using a permanent TDatabase component is that a permanent connection can be established, with the ability to manage transactions, you can create a BDE alias for your application, and you can respond to the ONLogin event.
The function of the temporary TDATABASE component has some level of limitations, and some of its key attributes are subject to the BDE session period it belong, for example, the KeepConnections property of the BDE session period determines whether the database continues when all data sets are turned off. Maintain in the connection state. The KeepConnections attribute of the permanent TDatabase component is not affected by the KeepConnections property of the BDE session period.
Sometimes, it is often difficult to determine that you need to use several TDatabase components, and you don't want to use a temporary TDatabase component instead, this time you need to dynamically create a TDATABASE component during run.
To create a TDATABASE component dynamically at runtime, you first want to declare a TDATABASE type variable, then call TDatabase's CREATE functions to create a TDATABASE object instance. The program is now as follows:
Function runtimedbcreate (Const DatabaseName: 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 dam
Begin
Tempdatabase: = TDATABASE.CREATE (Self);
Tempdatabase.Database.comasename: = DatabaseName;
Tempdatabase.SessionName: = sessionname;
Tempdatabase.keepConnection: = true;
END;
Result: = OpenDatabase (DatabaseName);
END;
Except
Tempdatabase.free;
Raise;
END;
END;
You can call the runtimedbcreate function like this:
VAR
MyDatabase: array [1..10] of tdatabase; mydbcount: integer;
Begin
MYDBCOUNT: = 1;
...
MyDatabase [mydbcount]: = runtimedbcreate ('MyDB' INTOSTR (MYDBCOUNT), '');
INC; MYDBCOUNT
...
END;
5.2 Control connection
Whether it is a permanent TDATABASE component or a temporary TDATABASE component, you can control the behavior of the connection database through their properties, methods, and events, which is also the main purpose of using the TDATABASE component.
5.2.1 Specify a BDE session period
All TDATABASE components must specify a BDE session period that it belongs, which is used to use two properties, one is sessionname, the other is session.
The sessionName property is used to specify the name of a BDE session period. When a TDATABASE component is placed on the form or data module in the design period, its sessionName property is automatically set to "default", which is the name of the default BDE session. If you have already put a number of Tsession components on the form or data module, you can select the value of the sessionName property from a drop-down list.
The session attribute is read-only and used to return the BDE session period object to which the TDATABASE component belongs. If the sessionname property is set to empty or "default", the session property returns the default BDE session period.
After returning the BDE session period by the Session property, you can access the property, methods, and events of TSession, even if you don't know the actual name of the BDE session.
5.2.2 Specify the database to be accessed
To specify a database, you should use the aliasName property or the drivername property. These two attributes are mutually exclusive, set one, and the other is emptied. Modify AliasName, DRIVERNAME, DATABASENAME, etc., you must first set the connezed property to false before you have, otherwise the exception is triggered.
The AliasName property is used to specify an alias for a database, which can only be set to existing BDE alias such as dbdemos, defaultdb, iblocal, etc.
The aliasing of the database is typically defined with SQL Explorer or BDE administrator. However, you can also define an app-specific alias with the DatabaseName property. The DatabaseName property can be set to an existing BDE alias. For Paradox and DBase tables, you can also be set to the path where the table is located.
The alias defined by the DatabaseName property is limited to use in this application, which will appear in the drop-down list of the DatabaseName property of the TTable, TQuery, TSTOREDPROC components.
The DRIVERNAME property is used to specify a type of database driver that can be set to Standard (for DBASE and PARADOX), MSSQL, Interbase, Oracle, Sybase, Informix, etc. After setting the DRIVERNAME attribute, you have to set the params property to specify the connection parameters.
The database driver is actually a parameter of the BDE alias. Therefore, after the AliasName property is set, DriverName will automatically empty. Conversely, after the drivername property is set, the aliasName property will be emptied, otherwise there will be contradictions. This seems that the drivername property does not seem to have, as long as the AliasName property is enough. However, when the DatabaseName property defines an app-specific alias, you need to set the drivername property to specify what driver used by the alias.
In the design period, you want to specify a BDE alias or database driver or define a dedicated alias, or both in the object viewer, you can also double-click the TDATABASE component to open the database properties editor, then set the DatabaseName property in the "Name" box. The value, set the value of the Alias property 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 property in the runtime, for example:
Database1.DatabaseName: = Edit1.Text;
5.2.3 Setting the parameters of the BDE alias
To set the parameters of the BDE alias, such as paths, server names, cache lengths, language drivers, user names, passwords, etc., you are using the params property.
In the design period, there are three ways to set the parameters of the BDE alias:
First, use SQL Explorer or BDE Administrator to define or modify alias and parameters.
The second is to open the String List Editor on the Object Observer Editor, and then type the name and value of the parameters in the format.
The third is to double-click the TDATABASE component to open the database properties editor, as shown in Figure 5.1.
Figure 5.1 Setting the parameters of the BDE alias
Click the "Default" button 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 more , Including server name, username, password, language driver, etc.
Click the "Clear" button to empty the "parameter overrides" box is the params property.
You can modify the parameters directly in the "Parameter Overrides" box, or add new parameters.
To set the parameters of the BDE alias at the runtime, you should use the TStrings object. As can be seen from Figure 5.1, the params property is actually a string list, and the format of each string is "Name = value". The program is now as follows:
With database1 do
Begin
Params.clear;
Params.Add ('username = sysdba);
Params.Add ('password = 1234');
LoginPrompt: = false;
Open;
END;
5.2.4 Log in to the server
Most servers have strict security measures to prevent unauthorized access. For the user, the first level of the level he face is logging in, that is, enter the username and password.
In the design period, when trying to connect to a remote server, Delphi 4 will launch a standard login dialog to allow you to enter your username and password.
There are three ways to log in during the running period:
The first way is to set the LoginPrompt property to True so that when a remote server is needed, a standard login dialog is automatically popped up, allowing the user to enter the username and password.
The second way is to set the LoginPrompt property to false and set the params attribute, which should contain "user name" and "password" parameters, for example:
User name = sysdbaPassword = masterkey
Note: Providing usernames and passwords in the program are easy to discure, it is recommended not to use this way.
The third way is to set the loginparams parameter in the handle of the ONLogin event, and the program is as follows:
Loginparams.values ['user name "]: = username; loginparams.values [' password ']: = passwordsearch (username);
When exiting the handle of the ONLogin event, the value of the loginparams parameter is assigned to the params property.
5.2.5 Start connecting the database server
To start connecting to the database server, you can call the Open function or set the connezted property to true. In fact, set the connect property to TRUE to automatically call the OPEN. At this point, the ONLOGIN event will be triggered. If the program does not process the ONLogin event, a standard login dialog will pop up to log in.
If you try to open a dataset without the connection server, you will first call the Open function to connect the server and automatically create a temporary TDatabase component as needed.
Once the connection is established with the server, as long as there is at least one data set is active, the connection will remain. If all the data sets are not active, whether the disconnect connection depends on the value of the KeepConnections property.
If the KeepConnections property is set to True, even if there is no data set in an active state, it is also possible to avoid logging in for applications that frequently open and close the dataset. If the KeepConnections property is set to false, the connection to the server will be disconnected when all the data sets are turned off.
To disconnect, call CLOSE or set the Connected property to false. In fact, set the Connected property to False automatically calls Close.
Close automatically closes all datasets and disconnects. If you just want to close all the datasets, don't want to disconnect, first set the KeepConnections property to true, then call the ClosedataSets function.
Note: Even if the KeepConnections property is set to True, call the Close function can always disconnect.
5.2.6 Network Agreement and ODBC
Delphi 4 uses BDE and SQL Links drivers to connect to the database server, where BDE can also drive the ODBC access to a wider range of data sources.
Pay attention to the problem of the network protocol when configuring SQL Links and ODBC drivers. In most cases, the network protocol is configured by the client software of the database server, but for ODBC, it is also necessary to configure a network protocol in a dedicated ODBC manager.
It is often difficult to succeed when you start to connect to the server. At this time, you first check if the client software is configured correctly. If you use the TCP / IP protocol, you want to check if you have installed the software such as Winsock.dll, the IP of the server. Whether the address is registered in the client's HOSTS file, whether the domain name service is configured correctly.
5.3 All datasets that travers a database
The DataSe component of the TDATABASE component and the DataSetCount property are combined with all the datasets that can be traversed.
The DataSets attribute is an array, and each element is an active data set such as TTABLE, TQUERY, or TSTOREDPROC, each accessible through the serial number.
DataSetCount Attributes Returns the number of elements in the DataSets array, and the program 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 TDATABASE and Tsession relationship The TDATABASE component is mainly used to manage the database's connection, while TSESSION is used to global control of the TDatabase component in an application, including temporary TDatabase components.
The method of TSession is often targeted for all TDATABASE components, it does not consider the status of the TDATABASE component. For example, Tsession's DropConnections function will close all datasets and disconnect all databases, even if the KeepConnections property of these TDATABASE components is set to True.
TDATABASE can only manage the database it is connected, for example, TDatabase's CloseDataSets function closes all data sets of a database, and does not close the data sets of other databases.