Multi-level database development four: BDE session

xiaoxiao2021-03-06  97

Chapter IV The BDE session period is a single layer, two layers or multi-layered database applications, generally used to use BDE (BORLANDDATABASE ENGINE). Delphi 4 uses TSession to manage BDE session periods, with TSessionList to manage and manipulate all BDE session objects in an application.

In general, it is not necessary to explicitly put the TSESSION component on the form or data module because the database application automatically creates a default BDE session period to serve session every time startup. However, if you develop a multi-threaded database application, you should explicitly use the TSESSION component because several threads are likely to connect to the database at the same time, and there should be another instance of the application to create an application every time you connect the database. .

4.1 Tsession

The TSession component can provide global control over a set of TDATABASE components within an application. When creating a database application (including the application server), the application automatically creates a default BDE session period called session. These components are automatically under the control of the default BDE session period, in the application, when adding new TDATABASE components and new data set components. In addition, the BDE session period can also provide passwords to access the ParaDox table, specify the directory where the network control file is located, and control the connection of the database.

In addition to the default BDE session period, some applications require additional TSession components. For example, if the application is parallel to query the same database, at this point, each query must have a separate BDE session period. Multi-threaded database applications also need multiple BDE sessions.

You can add TSESSION components in design period or dynamically create Tsession components during runtime.

4.1.1 Default BDE session object

All database applications automatically include a default BDE session period called session, its sessionname property is default. The default BDE session period can provide global control over all TDATABASE components, regardless of whether these TDATABASE components are explicitly added to the form or data module or during operation. Note: The default BDE session object does not exist in the design period, it only exists in the runtime.

Whether it is in the design period or when the TDATABASE component is added during the runtime, the added TDATABASE components are automatically managed under the default BDE session. Of course, if you explicitly use multiple Tsession components, you can also set the sessionName property of the TDatabase component to specify one of the TSession components.

The most important attribute of Tsession is KeepConnections, if this property is set to True, even if the data set is currently not opened, the connection to the database is maintained. In this way, the next time you open the data set, you don't have to log in to the database.

Note: The application must not try to delete the default BDE session period object.

4.1.2 Creating another BDE session object

In some cases you need to use additional BDE sessions. In the design period, you can add one or more TSESSION components to the form or data module, then set their properties to the object viewer, create an event handle, and call them. You can also create a BDE session period objectively in the running period.

To dynamically create a BDE session period, you can refer to the following steps:

The first step is to declare a variable of a TSESSION type.

The second step is to call the TSession's CREATE to create an object instance of TSESSION. CREATE automatically clears the Databases array, set the KeepConnections property to True, and add the newly created BDE session period to the list of BDE session-based objects managed by Sessions.

The third step is to set the sessionname property to specify the name of this BDE session period, and be careful not to be the same as the other BDE session period. TDATABASE and data set components are distinguished by name to distinguish BDE session. The fourth step is to activate this BDE session period, and then set the relevant properties.

The following program example creates a BDE session period, and finally deleted this BDE session object.

VAR SecondSession: tession;

Begin

SecondSession: = tession.create;

WITH SecondSession DO

Try

Sessionname: = 'SecondSession';

KeepConnections: = false;

Open;

...

Finally

SECONDSession.Free;

END;

END;

In fact, you can also call the TsessionList's OpenSession function to create a BDE session period, which needs to pass a sessionName parameter, specify the name of the BDE session period to create. If the BDE session period object that matches the sessionname parameter already exists, this function activates it. The program is now as follows:

Var mysession: tession;

MySession: = sessions.opensession ('Mysession ");

...

Mysis .free;

4.1.3 Name the BDE session period object

The TSession's sessionname property is used to name the BDE session period object. For the default BDE session object, its sessionname property is "default".

In the same application, the name of the BDE session period cannot be repeated. If the TSession's AutoSessionName property is set to true, Delphi 4 will automatically specify a different name for each BDE session period, so you don't have to worry about reign. If the AutoSessionName property is set to false, the application must set the sessionName property to specify a different name to each BDE session period. In the case where the AutoSessionName property is set to True, the value of the sessionname property cannot be directly modified.

However, there are many restrictions using the AutoSessionName attribute. For example, if there are multiple Tsession components on the form or data module, you cannot set the AutoSessionName property to True. If there is already a TSESSION component on the form or data module, and its autograSessionName property is set to TRUE, another TSESSION component cannot be added to the form or data module.

There is a sessionname property for TDATABASE components and data set components that specify a name of a BDE session. If their sessionname properties are empty, representation using the default BDE session period.

Below this example first call the OpenSession of TessionList to create a BDE session period object, then set the Database1's sessionName property Specify the BDE session period that is just created.

VAR

Ibsession: tession;

...

Begin

Ibession: = sessions.opensession ('interbasesis ";

Database1.SessionName: = 'interbasession';

END;

4.1.4 Activation BDE session period object

If the TSession's Active property returns true, it means that the BDE session period is active. If this property is set to True, the BDE session object will be activated and the onstartup event is triggered. Once the BDE session period is activated, you can call the OpenDatabase function to connect to the database.

Set the Active property to True, which is equivalent to calling Open. Set the Active property to false, which is equivalent to calling Close.

For the default BDE session period, it is preferred, it is best not to set its Active property to false.

When the BDE session period is activated, an onStartup event will be triggered, so it will set attributes such as NetFileDir, PrivateIr, and ConfigMode, but NetFileDir and PrivateIR properties are only valid only when accessing the Paradox table. The ConfigMode property is used to set which BDE alias is visible.

4.1.5 KeepConnections properties

If the KeepConnections property is set to TRUE, even if there is currently no dataset, the connection to the database is also maintained. If this property is set to False, the connection to the database is disconnected when all the data sets are turned off.

This attribute is for a dynamically generated temporary TDATABASE component, and if the TDATABASE component is explicitly used, it will be based on its KeepConnections properties.

If an application needs frequently opening and closing all datasets, especially when these datasets are on a remote server, it is best to set the KeepConnections property to TRUE, which avoids logging in to the remote server again. Otherwise, the application has to log in.

However, even if the KeepConnections property is set to TRUE, the DROPConnections function can still be invoked to disconnect the empty connection. The so-called empty connection refers to the current connection status because the KeepConnections property is now set to TRUE.

4.1.6 Opening and disconnecting

To open a connection to a database, call the OpenDatabase function. This function needs to pass a DatabaseName parameter, which is used to specify the name of the database to be opened, and can be set to the name of the BDE alias or TDATABASE component. For paradox or dbase, the DatabaseName parameter can also be set to the path where the table is located.

The following program example tries to open an aliasing database of DBDemos:

VAR

DBDemosDatabase: TDATABASE: TDATABASE;

Begin

DBDemosDatabase: = session.opendatabase ('dbdemos');

...

END;

OpenDatabase will first activate the BDE session period (if there is still no activation), then determine if the DatabaseName parameter matches the name of the TDatabase component managed by the BDE session period, if the matching database is not found, OpenDatabase will automatically create a temporary TDATABASE components. Finally, OpenDatabase calls TDatabase's OPEN connection database.

OpenDatabase actually adds an internal count to 1, as long as this count is greater than 0, the database is in connection.

You can call the CloseDatabase function to turn off a database. Like OpenDatabase, CloseDatabase also needs to pass a DatabaseName parameter to specify the database to be turned off, for example:

Session.CloseDatabase (dbdemosDatabase);

CloseDatabase is actually a reduction in an internal reference count. When the reference count is reduced to 0, the database is turned off. If the database specified by the DatabaseName parameter is managed by a temporary TDatabase component, and the KeepConnections property is set to FALSE, and the corresponding TDATABASE component is also deleted when the database is turned off.

In the case where the KeepConnections property is set to false, for those TDATABASE components that are temporarily created, if the database is currently not turned on, the database will be automatically turned off, and the TDATABASE component will be automatically deleted. For those TDATABASE components that explicitly add to the form or data module, you need to call Close to turn off the database.

If you want to close all the databases at a time, you can set the Active property of the BDE session object to false, or call the Close function. Set the Active property to false, will automatically call the Close, and Close closes all databases, remove all temporary created TDatabase components, then call those close-up TDATABASE, finally, set the handle of the BDE session period to NIL.

Before turning on and off, you may need to call the FindDatabase function to find if a specific database exists. The FindDatabase function needs to pass a DatabaseName parameter that specifies the database to be found, which can be set to the BDE alias or the name of the TDATABASE component. For Paradox or DBase tables, you can set the path where the table is located. If found, the FindDatabase function returns a TDATABASE component, otherwise, returns NIL. Below this example tries to search for an aliasing DBDemos database:

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 Retrieving information about the BDE session period

TSESSION provides many ways to retrieve information about the BDE session period such as an alias, etc., the following is briefly introduced.

.GetaliaSDrivername returns an alias driver;

.GetaliasNames returns a list of all BDE alias;

.GetaliaSparams returns a list of parameters of an alias;

.GetConfigParams returns specific information in the configuration file;

.GetDatabaseNames Returns a list of all BDE alias (including the alias that occupies);

.GetdriverNames Returns a list of installed drivers;

.GetDriverparams returns a driver parameter;

.GetStoredProcnames Returns the stored procedure name in a database;

.Gettablenames Returns the table name in a database.

In the above method, other methods are returned to a list in addition to GetaliaSdriverName returns a string. The following example tries to retrieve all BDE alias:

Var list: tstringlist;

Begin

List: = TSTRINGLIST.CREATE;

Try

Session.getDatabaseNames (List);

...

Finally

List.free;

END;

END;

4.3 Managing BDE alias

For BDE session objects, BDE alias is particularly important, and many methods need to pass a database alias as parameters. TSESSION provides the ability to manage BDE alias. 4.3.1 Specify the visibility of the alias

The ConfigMode property is used to set which BDE alias is visible to the BDE session. The configMode property is a collection. The default value is [cmall], which is equivalent to [cfmvirtual, cfmpersistent], indicating that all aliases are visible to the BDE session, including the alias defined in the BDE configuration file, the dedicated alias created by the BDE session .

The main purpose of using the ConfigMode property is to limit the visibility of the alias. For example, you can set the configMode property to [CFMVirtual], indicating that you can only see the alias created by this BDE session period, you can't see the alias created by other BDE sessions, and you can't see the permanent alias defined in the BDE configuration file.

The alias created during the BDE session only exists in memory. By default, only the BDE session period is visible, and other BDE sessions can see these alias even in the same application.

If you want to make an alias created by the BDE session to be seen by all BDE sessions, even other applications, first save the SaveConfigFile to save the alias into the BDE configuration file, so that other BDE sessions or other applications can use this Alias. Of course, the configMode attribute needs to be set to [CMALL].

4.3.2 Creating, modifying, and deleting alias

To create an alias for a SQL server, you can call the Addalias function. To create a local database such as Paradox, DBASE, or ASCII text alias, you can call the AddStandAlias ​​function.

Addalias needs to deliver three parameters, where the Name parameter is used to specify the name, which is used to specify the SQL Links driver, and the list parameter is used to specify the connection parameters. The program is now as follows:

VAR

AliaSparams: tstringlist;

Begin

AliaSparams: = TSTRINGLIST.CREATE;

Try

With aliaspamas 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, AddStandalias is used to create an alias for paradox, dbase, or text, and do not need to connect parameters, just specify a path and default driver. The program is now as follows:

AddStandardalias ('MydbDemos', 'C: / Testing / Demos /', 'Paradox');

To illustrate, the alias that calls the Addalias or AddStandAlias ​​function exists only in memory. To save the alias to the BDE configuration file, call the SaveConfigfile function.

Once you have created an alias, you can call ModifyAlias ​​to modify the parameters of the alias. ModifyAlias ​​needs to pass two parameters, one is the alias to modify, and one is a list of parameters to modify.

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 the Parameters of the CATS alias have several, only the parameters you want to modify are only included in the list of MODIFYALIAS.

To delete an alias created by a BDE session, you can call the Deletealias function. Deletealias only needs to pass a parameter, that is, the alias to delete.

Note: Calling the Deletealias function is just deleted from the memory. If the alias to delete is already in the BDE configuration file, you need to call the SaveConfigfile function after calling the Deletealias function.

4.4 Traversing all TDatabase components

This section describes two properties of TSession: Databases and DatabaseCount, which can be traversed all TDatabase components managed by a BDE session object with these two properties.

The Databases property is an array that is a TDatabase component in an active state, which is under the management of the BDE session object.

The DatabaseCount property is an integer that indicates the number of elements in the Databases array. As the database is turned on and off, the DatabaseCount property will automatically change. For example, in the case where the KeepConnections property is set to false and does not explicitly use the TDatabase unit, every time a database, the DatabaseCount property will add 1, and the DatabaseCount property will be reduced every time a database.

DatabaseCount properties are usually used with the Databases property. For example, the following code sets all the KeepConnection properties 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 Paradox Table

Tsession's NetFiledir property and privateIR properties are only available for Paradox tables. The NetFileDir property is used to specify the directory where the PARADOX network control file is PDOXUSRS.NET. Any application that needs to share the PARADOX table must specify the directory where this file is located. The privateIr property is used to specify a private directory for the Paradox table, and 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 property. You can also set this property to specify another legal network path. The program is now as follows:

Session.netFileDir: = extractFilepath (Application.exename);

Note: You can only modify the NetFileDir property without opening any Paradox tables yet.

If the privateDir property is empty, the BDE will automatically use the current directory as a private directory. If you want to run on a remote file server, in order to avoid the elderly to read and write file servers, it is best to set the privateDir property to a local drive. Note: You cannot set the privatedir property at the design period, otherwise, "Directory Busy" error occurs. Also, don't set the privateIr property to a root directory of a drive, it is best to be a subdirectory. The program is now as follows:

Session.PrivateIr: = 'c: / temp';

4.6 password

Some paradox tables and DBase tables need to be provided by password protection and passwords need to be provided when accessing them. TSESSION provides several methods and an event for administrative passwords.

4.6.1 AddPassword

Tsession's AddPassword function is usually called before accessing the Paradox or DBASE table that needs to enter the password. The only parameter of Addpassword is a password. The program is now 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 this example, call the inputbox function to enter the password, or call the PasswordDialog function, or use the TEDIT component to make an edit box, set the passwordchar attribute as an asterisk.

If you use the PasswordDialog function, you need to pass the BDE session period as a parameter, and the program is as follows:

Procedure TFORM1.BUTTON1CLICK (Sender: TOBJECT);

Begin

IF PasswordDialog (session) THEN

Table1.open

Else

ShowMessage ('NO Password Given, Could Not Open Table!');

END;

The above program will open a "Enter Password" dialog as shown in Figure 4.1.

Figure 4.1 Enter the password

The "Add" button on the dialog 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 the program, you must reference the DBPWDLG unit.

If you do not call the AddPassword or PasswordDialog function to provide a password, when accessing a password-protected paradox table and a DBASE table, the dialog box shown in Figure 4.1 is automatically popped up, allowing the user to enter the password.

4.6.2 RemovePassword and REMOVEAllpasswords

Tsession RemovePassword is used to delete a password previously entered by addpassword. RemovePassword only needs to pass a parameter, that is, the password to be deleted. The program is now as follows:

Session.RemovePassword ('1234');

The TSession's RemoveAllpasswords function is used to delete all previously entered passwords, and the program is as follows:

Session.RemoveAllpasswords; 4.6.3 onpassword and getpassword

When the program tries to open a password-protected paradox list, the event will be triggered, and the AddPassword function should be called in the handle of this event to enter a password, and then set the Continue parameter to True.

Calling a getPassword function will also trigger an onpassword event. The following example dynamically uses a method as a handle that handles the ONPassword event:

Procedure TFORM1. Formcreate (Sender: TOBJECT);

Begin

Session.onpassword: = password;

END;

Password also calls the inputbox function to open an input box to enter the password. If the user enters a 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 wrong, it still cannot open the Paradox table, so any code to open a paradox table must be able to handle exceptions.

Procedure TFORM1.OpenTablebtnClick (Sender: TOBJECT);

Const CRLF = # 13 # 10;

Begin

Try

Table1.Open; {will trigger onpassword event}

Except

ON E: Exception DO

Begin

ShowMessage ('Error!' CRLF E.MESSAGE CRLF);

Application.Terminate;

END;

END;

END;

4.7 Manage Multiple BDE Session Period

If you want to create a multi-threaded database application, you need to use multiple TSESSION components, and must be explicitly added to the form or data module in the design period, and ensure that their sessionName properties are different.

Delphi 4 manages and manipulates all BDE session period objects in an application, and automatically declares an Object Example Sessions for TSESSIONLIST.

If you want to create a new BDE session object, this is to use the OpenSession function of tessions. This function only needs to pass a parameter, that is, the name of the BDE session period to be created. The program is now as follows:

Sessions.openSession ('RuntimeSession' INTOSTR (sessions.count 1);

The above code ensures that the name of the BDE session period will not be repeated with the existing BDE session.

TessionList defines some properties and methods to manipulate the BDE session period, here is brief introduction:

.Count returns the number of BDE session performance, including activities and non-active;

.Findsession finds a specified BDE session object, if not found, return nil;

.GetSessionNames returns a list of sessionname properties of all BDE session periods;

.List can access a BDE session period by name by this property;

.OpenSession Dynamically creates a BDE session period;

.SESSIONS can access a BDE session period by serial number through this property.

In multi-threaded database applications, before opening a database, first check if this database has been opened by other threads. How to check? Use TSessionList's count attributes and sessions attributes to traverse all BDE session period objects, check if you contain the database you want to open by one by one, if any, indicating that this database is already open, That is, it is no longer to open the database during this BDE session, you have to replace a check.

If all BDE session objects are using this database, you must create a new BDE session object and then open the database.

转载请注明原文地址:https://www.9cbs.com/read-95946.html

New Post(0)