Multi-layer database development 4: BDE Session Period

Source: Internet
Author: User
Tags dbase
Chapter iv bde session
BDE (borlanddatabase engine) is generally used for single-tier, two-tier, or multi-tier database applications ). Delphi 4 uses tsession to manage BDE session objects and tsessionlist to manage and manipulate all BDE session objects in an application.
Generally, you do not need to explicitly place the tsession component on the form or data module, because the database application automatically creates a default BDE Session object called session at each start. However, if a multi-threaded database application is developed, the tsession component must be explicitly used, because several threads may need to connect to the database at the same time, avoid creating another instance of the application every time you connect to the database.
4.1 tsession
The tsession component can provide global control for a group of tdatabase components in an application. When you create a database application (including an application server), the application automatically creates a default BDE Session object called session. When a new tdatabase component and a new dataset component are added to an application, these components are automatically under the control of the default BDE Session Object (session. In addition, the BDE Session object can also provide a password to access the paradox table, specify the directory where the network control file is located, and control the database connection.
In addition to the default BDE Session object, some applications need to use other tsession components. For example, if an application needs to query the same database in parallel, each query must have a separate BDE session period. Multi-threaded database applications also require multiple BDE sessions.
You can either add a tsession component during the design period or dynamically create a tsession component during the runtime.
4.1.1 default BDE Session Object
All database applications automatically contain a default BDE Session object called session. Its sessionname attribute is default. The default BDE Session object can provide global control for all tdatabase components, regardless of whether these tdatabase components are explicitly added to the form or data module during the design period or are dynamically created during the runtime. Note: The default BDE Session object does not exist during the design period. It only exists during the runtime.
When tdatabase components are added during the design or runtime, the added tdatabase components are automatically managed under the default BDE session object. Of course, if you explicitly use multiple tsession components, you can also set the sessionname attribute of the tdatabase component to specify one of the tsession components.
The most important attribute of tsession is keepconnections. If this attribute is set to true, the connection to the database is maintained even if the dataset is not currently opened. In this way, you do not have to log on to the database the next time you open the data set.
Note: do not try to delete the default BDE session object.
4.1.2 create another BDE Session Object
In some cases, another BDE Session object is required. During the design period, you can add one or more tsession components to the form or data module, set their attributes in the object observer, create event handles, and call their methods. You can also dynamically create BDE session objects at runtime.
To dynamically create BDE session objects at runtime, follow these steps:
The first step is to declare a variable of the tsession type.
The second step is to call create of tsession to create a tsession object instance. Create will automatically empty the databases array, set the keepconnections attribute to true, and add the newly created BDE Session object to the list of BDE session objects managed by sessions.
Step 3: Set the sessionname attribute to specify the name of the BDE Session object. Note that it cannot be the same as that of other BDE sessions. Both tdatabase and dataset components differentiate BDE session objects by names.
Step 4: Activate the BDE Session Object and set relevant properties.
The following program example creates a BDE Session Object and deletes the BDE session object.
VaR secondsession: tsession;
Begin
Secondsession: = tsession. Create;
With secondsession do
Try
Sessionname: = 'secondsession ';
Keepconnections: = false;
Open;
...
Finally
Secondsession. Free;
End;
End;
In fact, you can also call the opensession function of tsessionlist to create a BDE Session object. This function needs to pass a sessionname parameter to specify the name of the BDE Session object to be created. If the BDE Session object that matches the sessionname parameter already exists, this function activates it. The program example is as follows:
VaR mysession: tsession;
Mysession: = sessions. opensession ('mysession ');
...
Mysession. Free;
4.1.3 name the BDE Session Object
The sessionname attribute of tsession is used to name BDE session objects. For the default BDE Session object, its sessionname attribute is "default ".
In the same application, the BDE Session object names cannot be repeated. If the autosessionname attribute of tsession is set to true, Delphi 4 automatically specifies a different name for each BDE Session object, so that duplicate names are unnecessary. If the autosessionname attribute is set to false, the application must set the sessionname attribute to specify a different name for each BDE session object. When the autosessionname attribute is set to true, you cannot directly modify the value of the sessionname attribute.
However, there are many restrictions on using the autosessionname attribute. For example, if the form or data module has multiple tsession components, the autosessionname attribute cannot be set to true. If the form or data module already has a tsession component whose autosessionname attribute is set to true, the other tsession component cannot be added to the form or data module.
Both the tdatabase component and the dataset component have a sessionname attribute to specify the name of a BDE session object. If their sessionname attribute is null, the default BDE Session object is used.
The following example first calls the opensession of tsessionlist to create a BDE Session object, and then sets the sessionname attribute of database1 to specify the newly created BDE session object.
VaR
Ibsession: tsession;
...
Begin
Ibsession: = sessions. opensession ('interbasesession ');
Database1.sessionname: = 'interbasesession ';
End;
4.1.4 activate BDE Session Object
If true is returned for the active attribute of tsession, The BDE Session object is active. If this attribute is set to true, the BDE Session object is activated and the onstartup event is triggered.
After activating the BDE Session object, you can call the opendatabase function to connect to the database.
Set the active attribute to true, which is equivalent to calling open. Setting the active attribute to false is equivalent to calling close.
For the default BDE Session object, that is, session, it is recommended not to set its active attribute to false.
When a BDE Session object is activated, the onstartup event is triggered, so that attributes such as netfiledir, privatedir, and configmode can be set. However, the netfiledir and privatedir attributes are valid only when accessing the paradox table. The configmode attribute is used to set which BDE aliases are visible.
4.1.5 keepconnections attributes
If the keepconnections attribute is set to true, the connection to the database is maintained even if no data set is currently opened. If this attribute is set to false, when all datasets are closed, the connection to the database is closed.
This attribute is applicable to dynamically generated temporary tdatabase components. If the tdatabase component is explicitly used, its keepconnections attribute prevails.
If an application needs to frequently open and close all datasets, especially when these datasets are on a remote data server, it is best to set the keepconnections attribute to true, this prevents you from logging on to the remote server again. Otherwise, the application has to log on again.
However, even if the keepconnections attribute is set to true, you can still call the dropconnections function to disconnect an empty connection. The so-called null connection means that no data set is opened currently, but the keepconnections attribute is set to true and remains in the connection status.
4.1.6 open and disconnect
To open a database connection, call the opendatabase function. This function needs to pass a databasename parameter to specify the name of the database to be opened, which can be set to the BDE alias or the name of the tdatabase component. For Paradox or dBase, The databasename parameter can also be set as the path of the table.
The following program example attempts to open a database with the alias dbdemos:
VaR
Dbdemosdatabase: tdatabase;
Begin
Dbdemosdatabase: = session. opendatabase ('dbdemos ');
...
End;
Opendatabase will automatically activate the BDE session phase (if not activated), and then determine whether the databasename parameter matches the name of the tdatabase component managed by the BDE session phase object, if no matching database is found, opendatabase automatically creates a temporary tdatabase component. Finally, opendatabase calls the Open Database of tdatabase to connect to the database.
Opendatabase actually adds 1 to an internal count. As long as the Count is greater than 0, the database is connected.
You can call the closedatabase function to close a database. Like opendatabase, closedatabase also needs to pass a databasename parameter to specify the database to be closed. For example:
Session. closedatabase (dbdemosdatabase );
Closedatabase actually reduces the internal reference count by 1. When the reference count is reduced to 0, the database is closed.
If the database specified by the databasename parameter is managed by a temporary tdatabase component and the keepconnections attribute is set to false, when the database is closed, the corresponding tdatabase component is also deleted.
When the keepconnections attribute is set to false, if the temporary tdatabase component is not opened, the database is automatically closed and the tdatabase component is automatically deleted. For the tdatabase components explicitly added to the form or data module, you must call close to close the database.
To close all databases at a time, you can set the active attribute of the BDE Session object to false or call the close function. When the active attribute is set to false, close is automatically called, and close closes all databases, deletes all temporarily created tdatabase components, and calls the close of explicitly used tdatabases in sequence, finally, set the BDE session handle to nil.
Before opening or closing a database, you may need to call the finddatabase function to check whether a specific database exists. The finddatabase function needs to pass a databasename parameter to specify the database to be searched. It can be set to the BDE alias or the name of the tdatabase component. For a paradox or DBASE table, it can be set as the path of the table. If it is found, the finddatabase function returns a tdatabase component. Otherwise, Nil is returned. The following example attempts to search for a database with the alias dbdemos:
VaR
DB: tdatabase;
Begin
DB: = session. finddatabase ('dbdemos ');
If (DB = nil) Then DB: = session. opendatabase ('dbdemos ');
If assigned (db) and DB. Active then
Begin
DB. starttransaction;
...
End;
End;
4.2 retrieve information about the BDE Session Period
Tsession provides many methods for retrieving information about BDE sessions, such as Alias parameters. The following describes these methods.
. Getaliasdrivername returns the driver of an alias;
. Getaliasnames returns a list Of all BDE aliases;
. Getaliasparams returns a list of parameters of an alias;
. Getconfigparams: Return specific information in the configuration file;
. Getdatabasenames: returns a list Of all BDE aliases (including occupied aliases );
. Getdrivernames: returns the list of installed drivers;
. Getdriverparams returns a driver parameter;
. Getstoredprocnames returns the name of the stored procedure in a database;
. Gettablenames returns the table name in a database.
In the preceding method, except getaliasdrivername, a string is returned. The following example attempts to retrieve all BDE aliases:
VaR list: tstringlist;
Begin
List: = tstringlist. Create;
Try
Session. getdatabasenames (list );
...
Finally
List. Free;
End;
End;
4.3 manage BDE aliases
For BDE session objects, BDE aliases are particularly important. Many methods require passing a database alias as a parameter. Tsession provides the BDE alias management function.
4.3.1 visibility of specified aliases
The configmode attribute is used to set which BDE aliases are visible to the BDE session. The configmode attribute is a set. The default value is [cmall], which is equivalent to [cfmvirtual, cfmpersistent], indicating that all aliases are visible to BDE sessions, this includes the alias defined in the BDE configuration file and the dedicated alias created during the BDE session.
The main purpose of using the configmode attribute is to restrict the visibility of aliases. For example, you can set the configmode attribute to [cfmvirtual], indicating that only the aliases created during the BDE session can be seen, and the aliases created during other BDE sessions cannot be seen, you cannot see the permanent alias defined in the BDE configuration file.
The alias created during the BDE session only exists in the memory. By default, it is only visible to the BDE session, these aliases cannot be seen in other BDE sessions even in the same application.
To enable the alias created during the BDE session to be viewed by all BDE sessions or even other applications, call saveconfigfile to save the alias to the BDE configuration file, other BDE sessions or other applications can use this alias. Of course, the configmode attribute must be set to [cmall].
4.3.2 create, modify, and delete aliases
To create an SQL Server alias, you can call the addalias function. To create an alias for a local database such as paradox, dBase, or ASCII text, you can call the addstandardalias function.
Addalias requires three parameters. The name parameter is used to specify the name, the driver parameter is used to specify the SQL links driver, and the list parameter is used to specify the connection parameter. The program example is as follows:
VaR
Aliasparams: tstringlist;
Begin
Aliasparams: = tstringlist. Create;
Try
With aliasparams do
Begin
Add ('Open mode = read ');
Add ('user name = tomstoppard ');
Add ('server name = animals:/cats/pedigree. GDB ');
End;
Session. addalias ('cats', 'intrbase', aliasparams );
Finally
Aliasparams. Free;
End;
End;
Unlike addalias, addstandardalias is used to create aliases for paradox, dBase, or text. You only need to specify a path and a default driver without connecting parameters. The program example is as follows:
Addstandardalias ('mydbdemos', 'c:/testing/demos/', 'paradox ');
Note that the alias created by calling the addalias or addstandardalias function only exists in the memory. to permanently Save the alias to the BDE configuration file, call the saveconfigfile function.
After creating an alias, you can call modifyalias to modify the alias parameters. Modifyalias requires two parameters, one is the alias to be modified, and the other is the list of parameters to be modified.
The following example sets the open mode parameter of the cats alias to read/write:
VaR
List: tstringlist;
Begin
List: = tstringlist. Create;
With list do
Begin
Clear;
Add ('Open mode = read/write ');
End;
Session. modifyalias ('cats', list); list. Free;
...
End;
Although there are several cats alias parameters, the list passed to modifyalias only needs to contain the parameters to be modified.
To delete an alias created during a BDE session, you can call the deletealias function. Deletealias only needs to pass one parameter, that is, the alias to be deleted.
Note: calling the deletealias function only deletes an alias from the memory. If the alias to be deleted has been permanently saved to the BDE configuration file, call the deletealias function and call the saveconfigfile function.
4.4 traverse all tdatabase Components
This section describes two attributes of tsession: databases and databasecount. These attributes can be used to traverse all tdatabase components managed by a BDE session object.
The databases attribute is an array. Each element of the database is an active tdatabase component that is under the management of BDE session objects.
The databasecount attribute is an integer that indicates the number of elements in the databases array. The databasecount attribute automatically changes as the database is opened and closed. For example, when the keepconnections attribute is set to false and the tdatabase component is not explicitly used, each time a database is opened, the databasecount attribute is added with 1, and each time a database is closed, the databasecount attribute is reduced by 1.
The databasecount attribute must be used with the databases attribute. For example, the following code sets the keepconnection attribute of all tdatabase components to true:
VaR
Maxdbcount: integer;
Begin
With session do
If (databasecount> 0) then
For maxdbcount: = 0 to (databasecount-1) do
Databases [maxdbcount]. keepconnections: = true;
End;
4.5 access the paradox table
The netfiledir attribute and privatedir attribute of tsession only apply to the paradox table. The netfiledir attribute is used to specify the directory where the paradox network control file is located, that is, the pdoxusrs. Net directory. All applications that need to share the paradox table must specify the directory where the file is located. The privatedir attribute is used to specify the private directory of the paradox table. Some temporary files are stored in the private directory.
Delphi 4 automatically retrieves the location of the network control file from the BDE configuration file and assigns it to the netfiledir attribute. You can also set this attribute to specify another valid network path. The program example is as follows:
Session. netfiledir: = extractfilepath (application. exename );
Note: The netfiledir attribute can be modified only when no paradox table is opened.
If the privatedir attribute is empty, BDE automatically uses the current directory as the private directory. If the application to be run is on a remote file server, it is best to set the privatedir attribute to a local drive to avoid the speed impact caused by reading and writing the file server.
Note: The privatedir attribute cannot be set during the design period. Otherwise, the "directory busy" error may occur. In addition, do not set the privatedir attribute to the root directory of a drive, preferably a subdirectory. The program example is as follows:
Session. privatedir: = 'C:/temp ';
4.6 orders
Some paradox tables and DBASE tables are password-protected. Passwords are required to access these tables. Tsession provides several methods and an event for password management.
4.6.1 addpassword
The addpassword function of tsession is generally called before accessing the Paradox or DBASE table that requires a password. It is used to provide a password. The unique parameter of addpassword is the password. The program example is as follows:
VaR
Passwrd: string;
Begin
Passwrd: = inputbox ('enter password', 'password :','');
Session. addpassword (passwrd );
Try
Table1.open
Except
Showmessage ('could not open table! ');
Application. Terminate;
End;
End;
In the preceding example, the inputbox function is called to allow the user to enter the password. You can also call the passworddialog function, or use the tedit component to create an edit box to set the passwordchar attribute to an asterisk.
If you use the passworddialog function, you need to pass the BDE Session object as the parameter. The program example is as follows:
Procedure tform1.button1click (Sender: tobject );
Begin
If passworddialog (Session) then
Table1.open
Else
Showmessage ('no password given, cocould not open table! ');
End;
The above program opens a "Enter Password" dialog box, as shown in 4.1.
Figure 4.1 enter a password
The "add" button on the dialog box is equivalent to calling the addpassword function. The "Remove" button is equivalent to calling the removepassword function. The "Remove all" button is equivalent to the removeallpasswords function.
Note: To Call The passworddialog function in a program, dbpwdlg units must be referenced.
If you do not call the addpassword or passworddialog function to provide a password, When you access the password-protected paradox table and DBASE table, the dialog box shown in 4.1 is displayed automatically, asking the user to enter the password.
4.6.2 removepassword and removeallpasswords
Removepassword of tsession is used to delete a password previously entered with addpassword. Removepassword only needs to pass one parameter, that is, the password to be deleted. The program example is as follows:
Session. removepassword ('20140901 ');
The removeallpasswords function of tsession is used to delete all previous passwords. The program example is as follows:
Session. removeallpasswords;
4.6.3 onpassword and GetPassword
This event is triggered when the program tries to open a password-protected paradox table. You should call the addpassword function in the handle to handle this event to enter a password and set the continue parameter to true.
Calling the GetPassword function also triggers the onpassword event. The following example uses a method dynamically as the handle to handle the onpassword event:
Procedure tform1. formcreate (Sender: tobject );
Begin
Session. onpassword: = password;
End;
Password also calls the inputbox function to open an input box and ask the user to enter the password. If the user enters the password, set the continue parameter to true.
Procedure tform1.password (Sender: tobject;
VaR continue: Boolean );
VaR passwrd: string;
Begin
Passwrd: = inputbox ('enter password', 'password :','');
Continue: = (passwrd> '');
Session. addpassword (passwrd );
End;
If the password entered by the user is incorrect, the paradox table cannot be opened. Therefore, the code to open a paradox table must be able to handle the exception.
Procedure tform1.opentablebtnclick (Sender: tobject );
Const CRLF = #13 + #10;
Begin
Try
Table1.open; {onpassword event will be triggered}
Except
On E: exception do
Begin
Showmessage ('error! '+ CRLF + E. Message + CRLF );
Application. Terminate;
End;
End;
End;
4.7 manage multiple BDE session objects
To create a multi-threaded database application, you must use multiple tsession components and add them to the form or data module explicitly during the design period, make sure that their sessionname attributes are different.
Delphi 4 uses tsessionlist to manage and manipulate all BDE session objects in an application, and the tsessionlist object example sessions has been automatically declared.
To dynamically create a new BDE Session object, use the opensession function of tsessionlist. This function only needs to pass a parameter, that is, the name of the BDE session to be created. The program example is as follows:
Sessions. opensession ('runtimesession' + inttostr (sessions. Count + 1 ));
The above Code ensures that the BDE session name does not repeat the existing BDE session name.
Tsessionlist defines some attributes and methods used to manipulate BDE session objects. Here is a brief introduction:
. Count returns the number of objects in the BDE session period, including active and inactive objects;
. Findsession searches for a specified BDE Session object. If not, Nil is returned;
. Getsessionnames returns a list of all the sessionname attributes of the BDE session object;
. List through this attribute, you can access a BDE Session object by name;
. Opensession dynamically creates a BDE session object;
. Sessions uses this attribute to access a BDE Session object by sequence number.
In a multi-threaded database application, before opening a database, you must first check whether the database has been opened by other threads. How to check? Use the count and sessions attributes of the tsessionlist to traverse all BDE session objects and check whether the databases attribute of each BDE Session object contains the database to be opened one by one. If yes, this indicates that the database has been opened by a thread. That is to say, you cannot open the database during the BDE session period. You have to change to another thread before checking.
If all BDE session objects use this database, you must create a new BDE Session object and then open the database.

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.