Whether it is a single layer, two layers are still multi-layered database applications, generally used to 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 TSession components 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, in the application. 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 The default BDE session Period All database applications automatically contain 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 an additional BDE session period Some of the cases need to be used 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 TSESSION type variable. 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: TSession; BeginSecondSession: = TSession.Create; With SecondSession DoTrySessionName: = 'SecondSession'; KeepConnections: = False; Open; ... FinallySecondSession.Free; End; End; in fact, it may be a function call TSessionList of OpenSession Create a BDE session period, this function needs to pass a sessionName parameter, specify the name of the BDE session object to be created. If the BDE session period object that matches the sessionname parameter already exists, this function activates it. The program is as follows: var mysession: tession; mysession: = sessions.opensession ('mysession "; ... Mysession.free; 4.1.3 Give the BDE session period object Name Tsession SESSIONNAME attribute to name the BDE session target 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. Varibsession: Tession; ... beginibsession: = sessions.opense; Database1.SessionName: = 'interbasession'; end; 4.1.4 Activating BDE session period If the TSession's Active property returns true, indicating the BDE session period Objects are 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 no dataset is not opened, it is also kept connected to the database. 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 the connection To open a database connection, 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 database: VardbDemosDatabase: tdatabase; begindbdemosDatabase: = session.opendatabase ('dbdemos'); ... End; OpenDatabase will first automatically activate the BDE session period (if there is still no activation), then It is determined whether 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 component. 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; CloseDatabase is actually reduced to a reference count count, when the reference count is reduced to 0, the database is only 0 is closed.
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 aliasing DBDemos: Vardb: tdatabase; begindb: = session.FindDatabase ('dbdemos'); if (db = nil) THEN DB: = session.opendatabase ('dbdemos'); if Assigned (DB); if Assigned ) and DB.Active the 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, such as the parameters of the alias, etc., the following brief introduction these method. .GetaliaSDriverName returns a driver of an alias; .GetaliasNames returns a list of all BDE alias; .Getaliasparams returns a list of alias parameters; .GetConfigParams returns specific information in the configuration file; .GetDatabaseNames Returns a list of all BDE alias (including occupied Alias); 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 search all BDE alias: var list: tstringlist; beginlist: = tstringlist.create; tryness.getDatabaseNames (list); ... finallyList.Free; end; end; 4.3 Managing BDE alias for BDE session Said that the BDE alias is particularly important, 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 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. Program example: varAliasParams: TStringList; BeginAliasParams: = TStringList.Create; TryWith AliasParams DoBeginAdd ( 'OPEN MODE = READ'); Add ( 'USER NAME = TOMSTOPPARD'); Add ( 'SERVER NAME = ANIMALS: / CATS / PEDIGREE. GDB '); END; session.addalias (' cats', 'intrbase', aliaasparams); FinallyAliasparams.free; end; end; Different from Addalias, AddStandalias is used to create alias for paradox, dbase or text, no need to connect Parameters, only need to specify a path and the default driver. The program example is as follows: Addstandardalias ('mydbdemos', 'C: / Testing / Demos /', 'Paradox'); to explain that the alias that calls the Addalias or AddStandArias function creates only in memory, you want to save the alias permanently 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.
Below this example sets the Open mode parameters of the CATS alias: Varlist: tstringlist; beginlist: = tstringlist.create; with list dobeginclear; 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 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 Traveling All TDatabase Components This section describes two attributes of TSession: Databases and DatabaseCount, with these two properties can be traversed by all TDatabase components managed by a BDE session object. 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 member TDatabase KeepConnection all attributes set True: varMaxDbCount: Integer; BeginWith Session DoIf (DatabaseCount> 0) thenFor MaxDbCount: = 0 to (DatabaseCount - 1) DoDatabases [MaxDbCount] .KeepConnections: = True; End 4.5 Access Paradox Table Tsession NetFiledIr attributes 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. Sample examples are as follows: session.netFileDir: = extractFilePath (Application.exename); Note: You can only modify the NetFileDir property without opening any paradox tables currently. 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 example is as follows: session.privateir: = 'c: / temp'; 4.6 ports Some paradox tables and dbase tables are password protected 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 typically calls before accessing the Paradox or DBASE table that you need to enter a password is used to provide passwords. The only parameter of Addpassword is a password. Program example: varPasswrd: String; BeginPasswrd: = InputBox ( 'Enter password', 'Password:', ''); (! Could not open table '); Session.AddPassword (Passwrd) Try Table1.OpenExcept ShowMessage'; Application .TERMINATE; END; END; The input inputbox function in this example allows the user to enter the password, or call the PasswordDialog function, or use the TEDIT component to make an edit box, set the passwordchar property to an asterisk. If, then, need to pass by PasswordDialog BDE SESSION object as a function of the parameter, the following exemplary procedure: Procedure TForm1.Button1Click (Sender: TObject); BeginIf PasswordDialog (Session) then Table1.OpenElse 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 The "Add" button on the input password 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 REMOVEACPASSWORDS TSession RemovePassword used to delete a password previously entered previously using AddPassword. RemovePassword only needs to pass a parameter, that is, the password to be deleted.
The program example is as follows: session.removepassword ('1234'); Tsession RemoveAllpasswords function is used to delete all previously input passwords, program examples are as follows: session.removeAllpasswords; 4.6.3 onpassword and getpassword When the program tries to open a password-protected Paradox The event is 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 of processing an onpassword event: Procedure TFORM1; beginsession.onpassword: = password; end; password calls the inputbox function Open a input box to let the user enter the password, if the user If you enter a password, set the Continue parameter to True. Procedure TForm1.Password (Sender: Tobject; Var Passwrd: String; Beginpasswrd: = INPUTBOX ('Enter Password', 'Password:', '); Continue: = (Passwrd>'); session .Addpassword (password); end; if the password entered by the user is wrong, you 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; BeginTryTable1.Open; {OnPassword event triggers} ExceptOn E: Exception DoBeginShowMessage ( '! Error' CRLF E.Message CRLF); Application .TERMINATE; END; END; END; 4.7 Managing Multiple BDE Session When you want to create a multi-threaded database application, you need to use multiple TSESSION components, and must be explicitly added to forms or data during design. On the module, it is also necessary to 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 example is as follows: sessions.opensession ('runtimesis' INTSTOSTR (sessions.count 1)); the above code ensures that the name of the BDE session period will not be repeated with the existing BDE session.