Scripting QTP - Ch08 - Adodb
Scripting QTP - Ch08 - Adodb
3 ADOX.............................................................................................................................. 3 WHERE IS THE DOCUMENTATION THAT COMES WITH ADO? ............................................... 3 WHERE CAN I FIND ADO CONSTANTS DEFINITIONS? ............................................................ 4 SOLUTIONS FOR LOCAL DATA ACCESS ................................................................................. 4 THE ADODB OBJECT MODEL ............................................................................................... 5 ADO OBJECT MODEL SUMMARY ...................................................................................... 5 OLE DB ................................................................................................................................. 6 ODBC .................................................................................................................................... 7 ADODB.CONNECTION OBJECT ............................................................................................. 7 WHAT IS A CONNECTION OBJECT? .................................................................................... 7 ADODB.CONNECTION PROPERTIES AND METHODS .......................................................... 8 ADODB COMMAND OBJECT ............................................................................................... 20 ADODB COMMAND OBJECT, PROPERTIES AND METHODS............................................... 20 ADODB RECORD OBJECT ................................................................................................... 26 ADODB RECORD OBJECT, PROPERTIES AND METHODS .................................................. 27 ADODB RECORDSET OBJECT ............................................................................................. 33 ADODB RECORDSET OBJECT, PROPERTIES AND METHODS ............................................. 34 ADODB STREAM OBJECT ................................................................................................... 59 ADODB STREAM OBJECT, PROPERTIES AND METHODS................................................... 60 ADODB ERRORS COLLECTION OBJECT ............................................................................. 69 ADODB ERRORS PROPERTIES AND METHODS ................................................................ 69 ADODB ERROR OBJECT ..................................................................................................... 71 ADODB ERROR OBJECT PROPERTIES .............................................................................. 71 ADODB FIELDS COLLECTION OBJECT ............................................................................... 74 ADODB FIELDS COLLECTION, PROPERTIES AND METHODS............................................. 75 ADODB FIELD OBJECT ....................................................................................................... 78 ADODB FIELD, PROPERTIES AND METHODS ................................................................... 78 ADODB PARAMETERS COLLECTION OBJECT .................................................................... 83 ADODB PARAMETERS COLLECTION, PROPERTIES AND METHODS .................................. 84 ADODB PARAMETER OBJECT ............................................................................................ 85 ADODB PARAMETER OBJECT, PROPERTIES AND METHODS ............................................ 86 ADODB PROPERTIES COLLECTION OBJECT ...................................................................... 89 ADODB PROPERTIES COLLECTION, PROPERTIES AND METHODS ..................................... 89 ADODB PROPERTY OBJECT ............................................................................................... 90 ADODB PROPERTY OBJECT, PROPERTIES ....................................................................... 90 Q&A .................................................................................................................................... 91 ADODB CONNECTION USAGE ........................................................................................ 95 ADODB CONNECTION PROPERTIES ................................................................................ 97 HOW DO I USE THE CONNECTION OBJECT TO CONNECT TO A DATA STORE? ................... 98 HOW DO I USE THE CONNECTION OBJECT TO EXECUTE A COMMAND?............................ 99 HOW TO CONNECT TO QUICKTEST DEMO FLIGHT RESERVATION APPLICATION USING A CONNECTION STRING?....................................................................................................100 HOW TO ADD A NEW RECORD TO A TABLE?...................................................................101
HOW TO SAVE A RECORDSET IN XML FORMAT? ............................................................101 LIST THE TOP X RECORDS IN A RECORDSET....................................................................102 HOW TO SEARCH FOR A RECORD IN A RECORDSET? .......................................................103 LIST THE TOP X RECORDS IN A RECORDSET....................................................................104 HOW TO SEARCH RECORDS WITH MULTIPLE CRITERIAS? ...............................................104 HOW TO CREATE AND DELETE A DSN?..........................................................................105 HOW CAN I GET A LIST OF THE ODBC DRIVERS THAT ARE INSTALLED ON A COMPUTER? ......................................................................................................................................107 HOW CAN I RETRIEVE A LIST OF THE SYSTEM DSNS ON A COMPUTER? .........................107 APPENDIX 14.A ADODB CONSTANTS ..............................................................................107 ADODB CONSTANTS.....................................................................................................107
ActiveX Data Objects are a language-neutral object model that expose data raised by an underlying OLE DB Provider. The most commonly used OLE DB Provider is the OLE DB Provider for ODBC Drivers, which exposes ODBC Data sources to ADO. ADO is a Microsoft technology. ADO stands for ActiveX Data Objects. ADO is a Microsoft Active-X component ADO is automatically installed with Microsoft IIS ADO is a programming interface to access data in a database Microsoft ActiveX Data Objects (ADO) enables your client applications to access and manipulate data from a variety of sources through an OLE DB provider. Its primary benefits are ease of use, high speed, low memory overhead, and a small disk footprint. ADO supports key features for building client/server and Web-based applications. Please see the Microsoft Web page for ADO Release Notes at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/dasdkadooverview.asp
http://www.devguru.com/technologies/ado
ADO DM
Microsoft ActiveX Data Objects (Multidimensional) (ADO MD) provides easy access to multidimensional data from languages such as Microsoft Visual Basic, Microsoft Visual C++, and Microsoft Visual J++. ADO MD extends Microsoft ActiveX Data Objects (ADO) to include objects specific to multidimensional data, such as the CubeDef and Cellset objects. With ADO MD you can browse multidimensional schema, query a cube, and retrieve the results. Like ADO, ADO MD uses an underlying OLE DB provider to gain access to data. To work with ADO MD, the provider must be a multidimensional data provider (MDP) as defined by the OLE DB for OLAP specification. MDPs present data in multidimensional views as opposed to tabular data providers (TDPs) that present data in tabular views. Refer to the documentation for your OLAP OLE DB provider for more detailed information on the specific syntax and behaviors supported by your provider.
RDS
Remote Data Service (RDS) is a feature of ADO, with which you can move data from a server to a client application or Web page, manipulate the data on the client, and return updates to the server in a single round trip.
ADOX
Microsoft ActiveX Data Objects Extensions for Data Definition Language and Security (ADOX) is an extension to the ADO objects and programming model. ADOX includes objects for schema creation and modification, as well as security. Because it is an object-based approach to schema manipulation, you can write code that will work against various data sources regardless of differences in their native syntaxes. ADOX is a companion library to the core ADO objects. It exposes additional objects for creating, modifying, and deleting schema objects, such as tables and procedures. It also includes security objects to maintain users and groups and to grant and revoke permissions on objects.
The Help file for ADO already installed in your computer! Look in Windows\Help, file name is ADO210.chm The documentation that comes with ADO is in html format and can be found by downloading the MDAC Software Development Kit (SDK) from the preceding Web site. Make sure to choose the Microsoft Data Access Components SDK Stand Alone Setup option when downloading MDAC 2.0, or the Microsoft Data Access Components SDK Update if downloading MDAC 2.1.
The documentation for the latest version of ADO is also available online at:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnmdac/html/datechartoverview.asp
Also, you can connect to the Microsoft Knowledge Base on the World Wide Web. To access the Microsoft Knowledge Base on the World Wide Web, visit the following Microsoft Web site:
http://support.microsoft.com/search
Description
Enables exchange of data. Embodies an SQL statement. Embodies a parameter of an SQL statement. Enables navigation and manipulation of data.
http://www.devguru.com/technologies/ado
Embodies a column of a Recordset object. Embodies an error on a connection. Embodies a characteristic of an ADO object.
Description
All the Error objects created in response to a single failure on a connection. All the Parameter objects associated with a Command object. All the Field objects associated with a Recordset object. All the Property objects associated with a Connection, Command, Recordset or Field object.
OLE DB
OLE DB (sometimes written as OLEDB or OLE-DB) is an API designed by Microsoft for accessing different types of data stores in a uniform manner. It is a set of interfaces implemented using the Component Object Model (COM); it is otherwise unrelated to OLE. It was designed as a higher-level replacement for, and successor to, ODBC, extending its feature set to support a wider variety of non-relational databases, such as object databases and spreadsheets that do not necesssarily implement SQL. OLE DB separates the data store from the application that needs access to it through a set of abstractions, such as connections, record sets and attributes. This was done because different applications need access to different types and sources of data and do not necessarily want to know how to access functionality with technology-specific methods. OLE DB is conceptually divided into consumers and providers. The consumers are the applications that need access to the data, and the provider is the software component that implements the interface. OLE DB is part of the Microsoft Data Access Components (MDAC) stack and is the database access interface technology. MDAC is a group of Microsoft technologies that interact together as a framework that allows programmers a uniform and comprehensive way of developing applications for accessing almost any data store. OLE DB providers can be created to access such simple data stores as a text file or spreadsheet, through to such complex databases as Oracle, SQL Server and Sybase. However, because different data store technology can have different capabilities, OLE DB providers may not implement every possible interface available to OLE DB. The capabilities that are available are implemented through the use of COM objects - an OLE DB provider will map the data store technologies functionality to a particular COM interface. Microsoft calls the availability of an interface to be "provider-specific" as it may not be applicable depending on the database technology involved. Additionally, however, providers may also augment the capabilities of a data store - these capabilities are known as services in Microsoft parlance.
ODBC
The Microsoft Open Database Connectivity (ODBC) interface is a C programming language interface that makes it possible for applications to access data from a variety of database management systems (DBMSs). The ODBC interface permits maximum interoperability an application can access data in diverse DBMSs through a single interface. Furthermore, that application will be independent of any DBMS from which it accesses data. Users of the application can add software components called drivers, which interface between an application and a specific DBMS. Many misconceptions about ODBC exist in the computing world. To the end user, it is an icon in the Microsoft Windows Control Panel. To the application programmer, it is a library containing data access routines. To many others, it is the answer to all database access problems ever imagined. First and foremost, ODBC is a specification for a database API. This API is independent of any one DBMS or operating system; although this manual uses C, the ODBC API is language-independent. The ODBC API is based on the CLI specifications from X/Open and ISO/IEC. ODBC 3.x fully implements both of these specifications earlier versions of ODBC were based on preliminary versions of these specifications but did not fully implement them and adds features commonly needed by developers of screen-based database applications, such as scrollable cursors. The functions in the ODBC API are implemented by developers of DBMS-specific drivers. Applications call the functions in these drivers to access data in a DBMSindependent manner. A Driver Manager manages communication between applications and drivers. Applications that use ODBC are responsible for any cross-database functionality. For example, ODBC is not a heterogeneous join engine, nor is it a distributed transaction processor. However, because it is DBMS-independent, it can be used to build such cross-database tools.
Connection.Attributes Property
The Attributes property sets or returns a long value defining the characteristics of a Connection object.
The Attributes property indicates the transaction attributes of a Connection object. It returns or sets a long value that is the sum of one or more of the XactAttributeEnum constants. The default is zero. Not all providers support this property. You can set multiple attributes by adding together the values. If you set the property value to an invalid sum, an error is generated. For a list of XactAttributeEnum constants see Table 1 on page 107
Connection.CommandTimeout Property
The CommandTimeout property sets the number of seconds to wait while attempting an Execute method call before terminating the attempt and generating an error message.
The CommandTimeout property defines how many seconds to wait before cancelling an Execute method call and generating an error. The default is 30 seconds. If you set CommandTimeout equal to zero seconds, the program will wait indefinitely or until the Execute is completed. The Command object has a similar property, but the two properties do not inherit from each other.
Connection.ConnectionString Property
The ConnectionString property sets or returns a string value that contains the details used to create a connection to a data source.
The ConnectionString property can be used to set or return a string that contains the information needed to establish a connection to a data source. The string is typically composed of a series of parameter=value statements that are separated by semicolons. After you complete the connection, the provider may alter these ADO parameter=value statements to the provider equivalents. Note that the ConnectionString string is also passed as part of the Open method call of the Connection object. ADO supports five arguments for the ConnectionString property; any other arguments pass directly to the provider without any processing by ADO. The arguments ADO supports are as follows: Argument
Provider= File Name= Remote Provider= Remote Server= URL=
Description
is the name of a file that contains the connection information. If you use this parameter, you cannot use the Provider= parameter. is the name of the provider. If you use this parameter, you cannot use the File Name= parameter. Specifies the name of a provider to use when opening a client-side connection. (Remote Data Service only.) Specifies the path name of the sever to use when opening a clientside connection. (Remote Data Service only.) is the absolute URL address to use for the connection.
After you set the ConnectionString property and open the Connection object, the provider may alter the contents of the property, for example, by mapping the ADO-defined argument names to their provider equivalents. Because the File Name argument causes ADO to load the associated provider, you cannot pass both the Provider and File Name arguments. The ConnectionString property is read/write when the connection is closed and read-only when it is open.
Duplicate parameters are ignored and only the last occurrence of a repeated parameter is used. Recommended site about ConnectionString from different providers can be found in : http://www.carlprothman.net/Default.aspx?tabid=81 and in http://www.connectionstrings.com/
Connection.ConnectionTimeout Property
The ConnectionTimeout property sets the number of seconds to wait while attempting to create a connection before terminating the attempt and generating an error message.
The ConnectionTimeout property sets or returns how many seconds to wait before cancelling a connection attempt and generating an error. The default is 15 seconds. However, heavy server use or high network traffic can easily cause delays greater than 15 seconds. If you set ConnectionTimeout equal to zero seconds, the program will wait indefinitely or until the connection is completed. This property must be set before the connection is established.
Connection.CursorLocation Property
The CursorLocation property sets or returns a long value used to select between various cursor libraries accessible through the provider.
The CursorLocation property establishes the cursor location and services. It sets or returns a long value that is one of the CursorLocationEnum constants. The default is adUseServer, or 2. Server-side and client-side provided cursor services usually add increased flexibility. For a list of CursorLocationEnum Values see Table 2 on page 107
Connection.DefaultDatabase Property
The DefaultDatabase property sets or returns a string value that is the default name of the database available from the provider for a Connection object.
Use the DefaultDatabase property to set or return the name of the default database on a specific Connection object. If there is a default database, SQL strings may use an unqualified syntax to access objects in that database. The DefaultDatabase property is used to set or return a string value that is the default database for a specific server-side connection. This property cannot be used with a client-side connection (Remote Data Service). Even if a default database is set, you may still open connections that access other databases. Tip To Retrieve the DefaultDatabase property the connection object must be
10
Connection.IsolationLevel Property
The IsolationLevel property sets or returns the transaction isolation level (the IsolationLevelEnum value) of a Connection object.
The purpose of the isolation level is to define how other transactions can interact with your transactions, and vice versa. For example, can you see changes in other transactions before or after they are committed? This property only goes into effect after you make a BeginTrans method call. This property sets or returns an IsolationLevelEnum value. If the requested level is not available, the provider may be able to set the IsolationLevel to the next higher level. For a list of IsolationLevelEnum Values see Table 3 on page 108
Connection.Mode Property
The Mode property sets or returns the provider access permission (the ConnectModeEnum value) for a Connection object.
The Mode property dictates the provider access permissions for an open connection. The Mode property must be set before the connection opened. This property sets or returns the ConnectModeEnum value. The default is adModeUnknown or zero. For a list of ConnectModeEnum Values see Table 4 on page 108
Connection.Provider Property
The Provider property sets or returns the string value that is the provider
11
name.
The Provider property used to set or return the name of the provider for a specific Connection object. The default is MSDASQL (Microsoft OLE DB provider for ODBC). The provider name can also be set using the ConnectString property of the Connection object and the ConnectString parameter of the Open method. You should never set the provider for a specific Connection in more than one place. Obviously, setting an invalid provider will generate an error.
Provider
Active Directory Services Microsoft Jet databases Microsoft Internet Publishing Oracle databases Simple text files Microsoft OLE DB provider for ODBC Microsoft Data Shape Locally saved files Microsoft SQL Server
Connection.State Property
The State property returns a long value describing if the connection is open or closed
The State property returns a long value that is the sum of one or more ObjectStateEnum constants. These constants describe if the Connection object is open, closed, or connecting. The adStateExecuting and adStateFetching constants are not used. The default value is adStateClosed. You can call the State property at any time. For a list of ObjectStateEnum Values see Table 5 on page 108
Connection.Version Property
The Version property returns a string value that is the ADO version number.
12
Use the Version property to return the version number of the ADO implementation. The version number of the provider is a dynamic property of the Properties collection.
Connection.BeginTrans Method
The BeginTrans method begins a new transaction and returns a long value indicating the number of nested transactions. Syntax object.BeginTrans
Begins a new transaction and returns a long value indicating the number of nested transactions. The BeginTrans method begins a new transaction. For example, a transaction could be a monetary transfer between two accounts. First, you would withdraw money from one account. Second, you would deposit the money into another account. Both actions must be correctly accomplished for such a transaction to be considered completed. This method can also be used to return a long value that is the level of nested transactions. A nested transaction is simply a transaction that occurs within a transaction. A top level transaction has a return value of 1 (one). Each additional level increments by one (the second level returns a 2, etc.). This method is only used to start a new transaction. Saving or cancelling a transaction requires the use of the CommitTrans and RollbackTrans methods. Not all providers allow transactions. You can search the Properties Collection to see if the Transaction DDL property occurs as part of the collection.
Connection.Cancel Method
The Cancel method Cancels the execution of a pending Execute or Open call. Syntax object.Cancel
The Cancel method used to cancel the last pending, asynchronous call involving either the Execute or the Open methods of the Connection object.
13
This requires that the Options parameter of the Open method be set to the adSyncConnect ADO constant or that the Options parameter of the Execute method be set to either the adAsyncExecute or adAsyncFetch ADO constant. Otherwise, a run-time error will be generated. An asynchronous call returns control to the calling program before the operation is completed and allows the execution of the code to continue.
Connection.Close Method
The Close method is used to close a Connection object and certain associated objects. Closing an Connection object does not delete it from memory. You can later use the Open method to reopen the same Connection. If there are open RecordSet objects associated with the Connection object being closed, then all of the RecordSet objects are automatically closed. There is also a rollback of all pending changes in the open RecordSet objects. Calling Close while a transaction is in progress will generate an error. If there is an open Command object associated with the Connection object being closed, the Command object remains open, but its ActiveConnection property is set to Nothing and it loses all association with the closed Connection. If you have closed an object and you no longer need it, you can set it equal to Nothing which will remove it from memory.
Connection.CommitTrans Method
The CommitTrans method saves any changes and ends the current transaction. It can also be set to automatically start a new transaction. Syntax object.CommitTrans
The CommitTrans method saves all pending changes made since the last BeginTrans method call was used to initiate a transaction. For example, a transaction could be a monetary transfer between two accounts. First, you would withdraw money from one account and next you would deposit the money into a second account. Both actions must be correctly accomplished for such a transaction to be considered completed.
14
Since transactions can be nested, all lower-level transactions must be resolved before you can resolve higher-level transactions. (i.e., level 3 transactions must be either committed or cancelled before level 2, etc.) This method is only used to save a new transaction. Beginning or cancelling a transaction requires the use of the BeginTrans and RollbackTrans methods. Not all providers allow transactions. You can search the Properties Collection to see if the Transaction DDL property occurs as part of the collection. The provider will automatically start a new transaction after a RollbackTrans call, if the Attributes property of the Connection object is set to adXactCommitAbort.
Connection.Execute Method
The Execute method executes the query, SQL statement, stored procedure, or provider-specific text. Syntax object.Execute (CommandText, RecordsAffected, Options) Arguments Parameter
CommandText RecordsAffected
Description
Required. A string that contains the specified query, SQL statement, stored procedure, or provider-specific text that you wish to execute. Optional. A Long variable to which the provider returns the number of records that the operation affected. Optional. defines how the provider should evaluate the CommandText parameter. It is a long value that is one or more of the CommandTypeEnum or ExecuteOptionEnum constants. The default is adCmdUnspecified or -1.
Options
The Execute method is used to execute the specified query, SQL statement, stored procedure, or provider-specific text. If it is a rowreturning query, the results (if any) will be stored in a new RecordSet object. If it is a non-row-returning query, the provider will return a closed RecordSet object. The default cursor is forward-only and read-only. You can use the CursorType property of the RecordSet object to choose other cursors. If the requested cursor is not available, the provider may choose another cursor. For a list of CommandTypeEnum Values see Table 7 CommandTypeEnum Values on page 109 For a list of ExecuteOptionsEnum Values see Table 6 ExecuteOptionEnum
15
Connection.Open Method
The Open method opens a connection to a data source. Syntax object.Open (ConnectionString, UserID, Password, Options) Arguments Parameter Description
Optional. a string that contains the information needed to establish a connection to a data source. The string is composed of a series of parameter=value statements that are separated by semicolons. Note that the ConnectionString property inherits the values from the ConnectionString parameter of this method. Optional. A string containing the user name to use when making the connection. Optional. A string containing the password to use when making the connection.
ConnectionString
UserID Password
Options
Optional. one of the ConnectOptionEnum constants which specify how the Connection object should return: synchronously (the default) or asynchronously.
Opens a physical connection to a data source. The Open method is used to establish (open) a physical connection to a data source. Once the connection is live, you can execute commands against the data source. ADO supports five arguments for this string. (This is the same format as the ConnectionString property.) Please refer to the ConnectionString Property for examples. Duplicate parameters are ignored and only the last occurrence of a repeated parameter is used. For a list of ConnectOptionsEnum Values see Table 8 ConnectOptionEnum Values on page 109
Connection.OpenSchema Method
The OpenSchema method returns descriptive schema information from the provider about the data source. Syntax object.OpenSchema (QueryType, Criteria, SchemaID)
16
QueryType
Criteria
SchemaID
Returns descriptive schema information from the provider about the data source. The OpenSchema method returns a read-only RecordSet object that contains schema (which means self-descriptive) information about the data source. For example, schema information can include the names of the tables, the names of the columns in the tables, and the data type of each column. The Criteria argument is an array of values that can be used to limit the results of a schema query. Each schema query has a different set of parameters that it supports. The constant adSchemaProviderSpecific is used for the QueryType argument if the provider defines its own nonstandard schema queries outside those in ShemaEnum. When this constant is used, the SchemaID argument is required to pass the GUID of the schema query to execute. If QueryType is set to adSchemaProviderSpecific but SchemaID is not provided, an error will result. Providers are not required to support all of the OLE DB standard schema queries. Specifically, only adSchemaTables, adSchemaColumns, and adSchemaProviderTypes are required by the OLE DB specification. However, the provider is not required to support the criteria constraints listed in SchemaEnum for those schema queries. For a list of SchemaEnum Values see Table 9 on page 112 Example
17
Option Explicit Const adSchemaTables = &H14 Const adSchemaColumns = 4 Const adStateOpen = 1 Dim oConn, oRst, oRstSchema Dim nRow Dim sColumn Set oConn = CreateObject("ADODB.Connection") '--- Opening Database via DNS oConn.Open "QT_Flight32" '--- Open schema Tables Set oRst = oConn.OpenSchema(adSchemaTables) Do Until oRst.EOF '--- Skip system tables If StrComp(oRst("TABLE_TYPE").Value, "SYSTEM TABLE") <> 0 Then sColumn = DataTable.LocalSheet.AddParameter( _ oRst("TABLE_NAME").Value, "").Name '--- Querying Schema table columns Set oRstSchema = oConn.OpenSchema(adSchemaColumns, _ Array(Empty, Empty, "" & oRst("TABLE_NAME").Value)) nRow = 1 DataTable.LocalSheet.SetCurrentRow nRow Do While Not oRstSchema.EOF DataTable(sColumn, dtLocalSheet) = _ oRstSchema("COLUMN_NAME").Value oRstSchema.MoveNext nRow = nRow + 1 DataTable.LocalSheet.SetCurrentRow nRow Loop End If oRst.MoveNext Loop '--- Close the recordset schema if opened. If oRstSchema.State = adStateOpen Then oRstSchema.Close '--- Close the recordset if opened. If oRst.State = adStateOpen Then oRst.Close '--- Close the connection if opened. If oConn.State = adStateOpen Then oConn.Close Set oRst = Nothing : Set oConn = Nothing : Set oRstSchema = Nothing
18
Connection.RollbackTrans Method
The RollbackTrans method cancels any changes that have occurred during the current transaction and then ends the transaction. It can also be set to automatically start a new transaction.
The RollbackTrans method cancels all pending changes made since the last BeginTrans method call used to initiate the transaction. For example, a transaction could be a monetary transfer between two accounts. First, you would withdraw money from one account and next you would deposit the money into a second account. Both actions must be correctly accomplished for such a transaction to be considered completed. Since transactions can be nested, all lower-level transactions must be resolved before you can resolve higher-level transactions. (i.e., level 3 transactions must be either committed or cancelled before level 2, etc.) This method is only used to cancel a new transaction. Beginning or saving a transaction requires the use of the BeginTrans and CommitTrans methods. Not all providers allow transactions. You can search the Properties Collection to see if the Transaction DDL property occurs as part of the collection. The provider will automatically start a new transaction after a RollbackTrans call, if the Attributes property of the Connection object is set to adXactCommitAbort.
19
Command.ActiveConnection Property
The ActiveConnection property Sets or returns a variant value defining the Connection object to which the Command object belongs, or returns a string value if there is no connection.
The ActiveConnection property is used to indicate the specific Connection object with which the Command object is to be associated and will use for execution. If the connection is closed, this property sets or returns a string that contains the definitions for the connection. If the connection is open, this property sets or returns a variant that is the Connection object to which the Command object is currently assigned.
20
The default is a null object reference. If you Set this property to a closed Connection object, an error will be generated. An error will also occur if you try to call the Execute method of the Command object before the connection is open. If you close the Connection that is associated with a Command object, the ActiveConnection property will be set to Nothing. If you set this property to Nothing, the Command object is disassociated from the Connection object. Note that both the Command and Connection objects will continue to exist. As long as both objects exist, you can use the ActiveConnection property to reset the same association, or set a new association between the Command object and another Connection object.
Command.CommandStream Property
The CommandStream property identifies the Stream object containing the command details.
The CommandStream property, new to ADO 2.6, identifies the Stream containing the command details. This can be any valid Stream object, or any object that supports the IStream interface. Note that the CommandStream and CommandText properties are mutually exclusive; setting one will clear the other.
Command.CommandText Property
The CommandText property sets or returns the text of a command statement to be applied against a data provider.
Sets or returns a String value containing a provider command, such as an SQL statement, a table name, or a stored procedure call. Default is "" (zero-length string). Use the CommandText property to set or return the text of a Command object. The SQL language must be a version that is supported by the provider. The default is the empty string "". If you need to use the same command repeatedly (even with different parameters) during a connection, set the Prepared property of the Command object to be True. This will cause the command to be compiled and stored for the life of the connection. Note that the CommandStream and CommandText properties are mutually exclusive; setting one will clear the other.
21
Command.CommandTimeout Property
The CommandTimeout property indicates how long to wait while executing a command before terminating the attempt and generating an error.
The CommandTimeout property defines how many seconds to wait before cancelling an Execute method call and generating an error. The default is 30 seconds. If you set CommandTimeout equal to zero seconds, the program will wait indefinitely or until the Execute is completed. The Connection object has a similar property, but the two properties do not inherit from each other.
Command.CommandType Property
The CommandType property sets or returns the CommandTypeEnum type of the Command object.
The CommandType property sets or returns a CommandTypeEnum constant that defines the type of the Command object. The default is adCmdUnknown. If the specific type declared using the CommandType property does not match the actual type of the Command object, an error will be generated when the Execute method is called. If you do not specify the type, ADO will need to contact the provider to determine the type of the command. In contrast, if you do specify the type, ADO will usually be able to process the command faster. This is a very simple, yet expedient way to optimize submitting a Command against a data source. You may also combine the adExecuteNoRecords constant from the ExecuteOptionEnum constants with the adCmdText or adCmdStoredProc constants of the CommandTypeEnum constants to speed up processing. For a list of ExecuteOptionEnum Values Table 6 on page 108 For a list of CommandTypeEnum Values see Table 7 on page 109
Command.Dialect Property
The Dialect property sets or returns the dialect to be used for the CommandStream or CommandText properties.
The Dialect property, new to ADO 2.6, sets or returns the dialect to be
22
used for the CommandStream or CommandText properties. This is a provider-independent Globally Unique IDdentifier which allows the provider to support multiple dialects. Its main use is in XML-generated Recordsets, where it identifies what form of XML the Recordset is stored in.
Command.Name Property
The Name sets or returns the string name of the Command object.
You can use the Name property to uniquely identify individual Command objects. The value must be set before you call the ActiveConnection property. The Name property is also used by the Field, Parameter, and Property objects. The Name property can also be obtained from the Properties Collection.
Command.NamedParameters Property
The NamedParameters property sets or returns a Boolean that determines whether or not parameter names should be passed to the provider.
The NamedParameters property, new to ADO 2.6, sets or returns a boolean that determines whether or not parameter names should be passed to the provider. The default value is False, meaning that parameters are interpreted in the order in which they were created. Changing the value of this property to True causes ADO to pass their names to the provider, which will then be used to match up the parameters. The former method, however, is more efficient because the provider does not have to do any matching.
Command.Prepared Property
The Prepared property sets or returns a Boolean value that indicates whether or not the provider is to save a compiled version of a command before it is executed.
The Prepared property sets or returns a Boolean value (True or False) that specifies whether or not to save a compiled version of a Command object before it is executed for the first time. If True, the compiled version is saved before the first execution and all subsequent executions involving this same Command will usually process
23
faster. This improved performance is very beneficial if you need use the same Command objects (albeit with different parameters) more than once. However, a stored procedure can even be more efficient for a large number of repeated executions of the same Command. Further, the amount of available memory will have to be considered, since each Prepared statement will have to be stored in a temporary database. If False, the Command object is executed without creating a compiled version. The default is False.
Command.State Property
The State property returns a long value describing if the Command object is open, closed or in the process of connecting, executing or retrieving.
The State property returns a long value that is the sum of one or more ObjectStateEnum constants. These constants describe if the Command object is open, closed, connecting, executing, or fetching. The default value is adStateClosed. You can call the State property at any time. For a list of ObjectStateEnum Values see Table 5 on page 108
Command.Cancel Method
The Cancel method cancels the execution of a pending Execute call. Syntax object.Cancel
The Cancel method is used to cancel the last pending, asynchronous call involving the Execute method of the Command object. The Options parameter of the Execute method must be set to either the adAsyncExecute or adAsyncFetch constant. Otherwise, a run-time error will be generated. An asynchronous call returns control to the calling program before the operation is completed and allows the execution of the code to continue.
Command.CreateParameter Method
24
Description
Optional. String that is the name of the Parameter object. Optional. One of the DataTypeEnum constants that specifies the data type for the Parameter object. If you choose a variable-length data type, you will need to also provide the size using either the Size parameter or the Size property. If you do not provide the Size, an error will be generated when you attempt to append the Parameter to the Parameters Collection. The default is adEmpty. Optional. One of the ParameterDirectionEnum constants that defines the direction (input vs. output, etc.) of the Parameter object. The default is adParamInput. Optional. A long value that specifies the length of a variable-length data type, if such a type was declared in the Type parameter. If you do not provide the Size for a variable-length data type, an error will be generated when you attempt to append the Parameter to the Parameters Collection. The default is zero. Optional. a variant that is the value of the Parameter.
Type
Direction
Size
Value
The CreateParameter method returns a Parameter object containing the specified name, type, direction, size, and/or value properties. The CreateParameter method does not automatically add (append) the new Parameter to the collection. If you wish to add a new Parameter to the Parameters Collection, you need to use the Append property. You can use CreateParameter without any parameters. You can later use the various appropriate properties of the Parameter object to add the name, type, direction, size and/or value. If you specify an adDecimal or adNumeric data type, you will also have to set the NumericScale and the Precision properties of the Parameter object. For a list of DataTypeEnum Values see Table 12 on page 117 For a list of ParameterDirectionEnum Values see Table 13 on page 117
Command.Execute Method
The Execute method executes the query, SQL statement or stored procedure. Syntax object.Execute ([RecordsAffected], [Parameters], [Options]) Arguments Parameter
RecordsAffected
Description
Optional. a long value returned by the provider that is the number of
25
records affected by an action query. (For a row-returning query, you will need to use the RecordCount property of the Recordset object to get a count of how many records are in the object.) Parameters Optional. Used to change, update, or insert new parameter values into the Parameters Collection assigned to the Command object. Optional. defines how the provider should evaluate the CommandText parameter. It is a long value that is the sum of one or more of the CommandTypeEnum or ExecuteOptionEnum constants. The default is adCmdUnspecified or -1.
Options
The Execute method returns a reference to a Recordset object. You use this method to execute the query, SQL statement, or stored procedure contained in the CommandText property of the Command object. If it is a row-returning query, the results are stored in a new Recordset object. If it is not a row-returning query, the provider will return a closed Recordset object. For a list of CommandTypeEnum Values see Table 7 on page 109 For a list of ExecuteOptionsEnum Values see Table 6 on page 108
26
Record.ActiveConnection Property
The ActiveConnection property sets or returns a variant value defining the Connection object to which the Record object belongs (or a string value if there is no connection).
The ActiveConnection property sets or returns a string definition for a connection if the connection is closed, or returns a variant that is a reference to an open Connection object. This allows you to determine which Connection object will be used by a Command object to execute a command query, or to which Connection object that a Recordset object will be applied (opened). The default is a Null reference object. You can also use the ActiveConnection parameter of the Open method of the Record object to set this property. When a Record is opened from an already existing Record or Recordset, it will automatically be set to the Connection object associated with the Record or Recordset. Similarly, when a Record object is opened from a URL, a Connection object is implicitly set.
Record.Mode Property
The Mode property sets or returns the provider access for a Record object.
The Mode property dictates the provider access permissions for an open connection. It must be set before the connection is opened. This property sets or returns the ConnectModeEnum value. The default is adModeUnknown. For a list of ConnectModeEnum Values see Table 4 on page 108
27
Record.ParentURL Property
The ParentURL property returns a string value that is the absolute URL of the record in the Record object.
The ParentURL property returns a string that is the absolute URL of the parent Record. An absolute URL is the path to the location of a resource on the Internet/Intranet. This property will return a null if there is no parent for the object or if the Record object cannot be represented by a URL.
Record.RecordType Property
The RecordType property returns a RecordTypeEnum that is the type of the Record object.
The RecordType property returns a RecordTypeEnum constant that specifies the type of the Record object. For a list of RecordTypeEnum Values see Table 20 on page 121
Record.Source Property
The Source property returns a variant value that is the source parameter of the Open method of the Record object.
The Source property sets or returns a variant that is the source of the entity represented by a Record object. This can be the relative or absolute URL string of the entity to be represented by the Record object, or a reference to an open Recordset object where an open Record represents the current row in the Recordset. When the Record object is open, this property is read-only and returns the Source parameter of the Open method of the Record object. When the Record object is closed, this property is read/write.
Record.State Property
The State property returns a long value describing if the Record object is open or closed.
28
The State property returns a long value that is the sum of one or more ObjectStateEnum constants. These constants describe if the Record object is open, closed, or executing. The adStateConnecting and adStateFetching constants are not used. The default value is adStateClosed. You can call the State property at any time. For a list of ObjectStateEnum Values see Table 5 on page 108
Record.Cancel Method
The Cancel method cancels the execution of a pending CopyRecord, DeleteRecord, MoveRecord, or Open call. Syntax object.Cancel
The Cancel method is used to cancel the last pending, asynchronous call involving the CopyRecord, DeleteRecord, MoveRecord, or Open methods of the Record object. The Options parameter of the Execute method must be set to either the adAsyncExecute or adAsyncFetch constant. Otherwise, a run-time error will be generated. An asynchronous call returns control to the calling program before the operation is completed and allows the execution of the code to continue. For a list of ExecuteOptionEnum Values see Table 6 on page 108
Record.Close Method
The Close method is used to close a Record object. As a consequence, you also lose access to any associated data. Closing a Record object does not delete it from memory. You can later use the Open method to reopen the same Record, with or without the same properties. If you have closed an object and you no longer need it, you can set it equal to Nothing which will remove it from memory. Calling the Close method while an edit is in process will generate an error.
29
Record.CopyRecord Method
The CopyRecord method copies a file, or a directory and its contents, to a specified location. Syntax object.CopyRecord ( Source, Destination, UserName, Password, Options, Async ) Arguments Constant
Source
Description
Optional. A string that is the URL of the file or directory that is to be copied. If you do not provide a value or provide the empty string, the default value will be the file or directory where the referenced Record object resides. Optional. A string that is the URL into which the file or directory is to be copied. The values of the Source and Destination parameters must be different, or a run-time error will occur Optional. A string that is the user name of a person who has authorization to access the destination locale. Optional. A string that is the password that authenticates the UserName parameter. Optional. A CopyRecordOptionsEnum constant that specifies the behavior of this method. The default is adCopyUnspecified. Optional. A Boolean value. If True, the operation can be asynchronous. If False, which is the default, the operation is synchronous
Destination
The CopyRecord method used to copy a file or a directory and its contents from a source location to a destination location. The default is, to not allow over write or recursive copy. If you do specify recursion, the destination location may not be a subdirectory of the source location. This method will return a string value that is usually the value of the Destination parameter, but the exact value that is returned is providerdependent. For a list of CopyRecordOptionsEnum Values see Table 21 on page 121
Record.DeleteRecord Method
The DeleteRecord method deletes a file, or a directory and all of its contents. After such a delete, you need to close the Record object.
30
Description
Optional. a string that is the URL of the file or directory that is to be copied. If you do not provide a value or provide the empty string, the default value will be the file or directory where the referenced Record object resides. Optional. a Boolean value. If True, the operation can be asynchronous. If False, which is the default, the operation is synchronous.
Async
Deletes a file, or a directory and all of its contents. After such a delete, you need to close the Record object. The DeleteRecord method is used to delete a file or a directory and all of its subdirectories. You are strongly advised to close the affected Record immediately after calling a DeleteRecord. This will prevent any future operations performed by the provider from causing unpredictable behavior before the next update.
Record.GetChildren Method
The GetChildren method returns a Recordset object where each row represents a file or directory. Syntax object.GetChildren
The GetChildren method returns a Recordset object where each row represents a file or subdirectory in the directory represented by the Record object. The provider dictates which columns are actually in the returned Recordset.
Record.MoveRecord Method
The MoveRecord method moves a file, or a directory and its contents, to a specified location. Syntax object.MoveRecord (
31
Description
Optional. A string that is the URL of the file or directory that is to be copied. If you do not provide a value or provide the empty string, the default value will be the file or directory where the referenced Record object resides. Optional. A string that is the URL into which the file or directory is to be copied. The values of the Source and Destination parameters must be different, or a run-time error will occur. Optional. A string that is the user name of a person who has authorization to access the destination locale. Optional. A string that is the password that authenticates the UserName parameter. Optional. A MoveRecordOptionsEnum constant that specifies the behavior of this method. The default is adMoveUnspecified. Optional. A Boolean value. If True, the operation can be asynchronous. If False, which is the default, the operation is synchronous
Destination
The MoveRecord method is used to move a file or a directory and its contents from a source location to a destination location. In effect, the file or directory is deleted from its current location. If you want the file or directory to remain at the source location, you can use the CopyRecord method to relocate a copy to another location. The default is not to overwrite any file or directory at the destination location and to update hypertext links in the files being moved, unless you specify otherwise in each case. Note that the ParentURL property is not automatically updated. You will need to close the Record and re-open it with the new URL. Likewise, you should close and re-open the Recordset object from which the Record was obtained to update the location. This method will return a String value that is usually the value of the Destination parameter, but the exact value that is returned is providerdependent. For a list of MoveRecordOptionsEnum Values see Table 22 on page 121
Record.Open Method
The Open method used to open an existing Record object, or to create a new file or directory. Syntax object.Open ( Source, ActiveConnection, Mode, CreateOptions, Options,
32
Description
Optional. a variant that is the absolute or relative URL of the entity represented by the Record, or it is a row of a Recordset object that is open. Optional. A variant that is the connection string or an open Connection object which specifies the file or directory that the Record object will be applied. If this property is not specified and Source is an absolute URL, then a Connection object is implicitly created using Source. If Source is a relative URL, then ActiveConnection must contain a Connection object, an absolute URL, or a Record that represents a directory. Optional. One or more of the ConnectModeEnum constants that declare the mode for the Record. The default is adModeUnknown. Optional. One or more of the RecordCreateOptionsEnum constants that specify whether to open an existing Record or to create a new one. The default is adFailIfNotExists. Optional. One or more of the RecordOpenOptionsEnum constants that specify the options for opening a Record object. The default is adOpenRecordUnspecified. Optional. A string that is the user name of a person who has authorization to access the destination locale. Optional. A string that is the password that authenticates the UserName parameter.
ActiveConnection
Mode
CreateOptions
Options
UserName Password
If The Open method is used to open an existing Record object or to create a new file or directory. For a list of ConnectModeEnum Values Table 4 on page 108 For a list of RecordCreateOptionsEnum Values Table 23 on page 122 For a list of RecordOpenOptionsEnum Values Table 24 on page 122
33
For example, some properties may not be available to the Recordset object depending on which provider is being accessed. You can use the Supports method to predetermine if a Recordset object will support a specific type of functionality.
Recordset.AbsolutePage Property
The AbsolutePage property sets or returns a long value that is the current page number in the Recordset object, or the PositionEnum value.
When you set this property to a page number, you will be moved to the first (top) record on the page you have specified. The AbsolutePage property may also return one of the PositionEnum constants. Note that you cannot set this property to any of the PositionEnum constants. The first page is always numbered one. You use the PageSize property to set how many records are on a page. You use the PageCount property to determine how many pages are in the
34
Recordset. You can only use this property if AbsolutePage, PageCount, and PageSize are all supported by the provider (i.e., bookmarks are supported). You must also be pointing to a valid record when attempting to use this property. If you are not pointing to a valid record, this property will return one of the PositionEnum constants, which specify the current position of the record pointer in the Recordset. For a list of PositionEnum constants see Table 25 on page 122
Recordset.AbsolutePosition Property
The AbsolutePosition property sets or returns a long value a long value that is the ordinal position of the cursor.
The AbsolutePosition property may also return one of the PositionEnum constants. Note that you cannot set this property to any of the PositionEnum constants. This property only points to a position and should not be used to uniquely identify a record, since additions, deletions, sorts and other operations can easily rearrange the contents of a recordset. When you set this property to a position number, you will be moved to the record at the position you have specified. In addition, the Recordset cache is reloaded. The records in the cache will now start at the numeric position in the Recordset you have specified. The total number of records that can be stored in the cache is set by the CacheSize property. The first record is always numbered one. You can use the RecordCount property to determine the total number of records in the Recordset. You can only use this property if it is supported by the provider. You must also be pointing to a valid record when attempting to use this property. If you are not pointing to a valid record, this property will return one of the PositionEnum constants which specify the current position of the record pointer in the Recordset. You may also need the set the CursorLocation property to adUseClient since the default for this property is adUseServer. For a list of PositionEnum constants see Table 25 on page 122 For a list of CursorLocation constants see Table 2 on page 107
Recordset.ActiveCommand Property
35
This is a convenient way to find the associated Command object even if you only have the resultant Recordset. However, if the Recordset was not created by a Command object, then a Null object is returned. You can use this property even after the Recordset has been closed.
Recordset.ActiveConnection Property
The ActiveConnection property sets or returns a variant defining the Connection object to which the Recordset belongs, or returns a string value if there is no connection.
The ActiveConnection property can be used to determine what Connection object is associated with the Recordset object. If the connection is closed, you can set or return a connection string that defines the connection. If the connection is open, you can set or return a variant that contains the Connection object associated with the Recordset. The default is a Null object reference. A client-side Recordset can only be set to a connection string or to Nothing. Setting this property to Nothing will disconnect the Recordset from the database. Since the Recordset will still exist, the contents can be examined. Also, it can later be reconnected. If you set this property to a valid connection string or to a valid Connection object, then the provider will create a new Connection object and open the connection. The ActiveConnection property can inherit the value of the ActiveConnection parameter of the Open method. In a similar fashion, the ActiveConnection property of the Recordset inherits the value of the ActiveConnection property of the Command object if the Source property of the Recordset object is set to a valid Command object.
Recordset.BOF Property
The BOF property returns a Boolean value indicating if the current record position is before the first record.
The BOF property returns a Boolean value that indicates if the current position in a Recordset object is just before the first record.
36
If True, you are at BOF. If False, you are at or beyond the first record, but still inside the Recordset. The companion EOF property returns a Boolean value that indicates if the current position in a Recordset object is just after the last record. If both the BOF and EOF properties are True, then there are no records in the Recordset. If you are at BOF, then you should not call the MovePrevious method. If you do, an error will be generated since there cannot be a previous record.
Recordset.Bookmark Property
The Bookmark property sets or returns a variant value that uniquely defines the position of a record in a Recordset.
The Bookmark property sets or returns a variant that uniquely marks the current record. This allows you to quickly return to that record, even after you have visited numerous other records in the same Recordset. Note that the actual value of the bookmark is not important and, even if you try, you may not be able to view the value. If you have created a copy of a Recordset using the Clone method, both the original and the clone will have the same bookmark. Unfortunately, not all providers support the Bookmark property. In this regard, support is cursor dependent. For example, server-side dynamic cursors do not support bookmarks, while client-side and static cursor usually do provide support.
Recordset.CacheSize Property
The CacheSize property sets or returns a long value that is the number of records that are cached or are allowed to be cached.
The CacheSize property sets or returns a long value that defines how many records can be stored in the local cache for the client. As you navigate through the Recordset, the cache will be continually refreshed. You can change the CacheSize any time the Recordset exists, but the contents in the cache will not be changed until the next retrieval from the database. The default value is one record which means that only one record is fetched and cached at a time. For a large database, this is not too efficient and a larger value (especially in the 10 to 100 range) will speed up operations. On the negative side, records stored in a cache may not reflect real-time underlying changes
37
being made to the database by other users. For example, your cache could contain records that have been recently deleted. Therefore, you may need to regularly call the Resync method which will also update the cache. A cache size of zero is not permitted and will generate an error.
Recordset.CursorLocation Property
The CursorLocation property sets or returns a long value that is a CursorLocationEnum value which defines the location of the cursor engine.
The CursorLocation property sets or returns one of the CursorLocationEnum constants that specifies the location of the cursor library. In reality, there are only two choices, client-side or server-side. Typically, client-side cursors are more versatile. However, the default is to the serverside. You cannot change the cursor library for a Recordset while it is open. For a list of CursorLocation constants see Table 2 on page 107
Recordset.CursorType Property
The CursorType property sets or returns a CursorTypeEnum value that defines the type of cursor being used..
The CursorType property sets or returns a CursorTypeEnum constant that specifies the type of cursor to use when you open a Recordset object. Unfortunately, not all types of cursors are recognized by all providers. If you request a cursor type that is not supported, the provider will probably change the type. The value of the CursorType property will be changed accordingly. After the Recordset is open, you cannot set the CursorType property. However, you can return the property to see which cursor is actually being used. For a list of CursorTypeEnum constants see Table 26 on page 122
Recordset.EditMode Property
The EditMode property returns an EditModeEnum value that defines the editing status of the current record.
38
describes the editing status of the current record. ADO stores this editing status information in an editing buffer. If you move to a current record that has been previously deleted or if you arrive at BOF or EOF, this property will return an error. For a list of EditModeEnum constants see Table 27 on page 107
Recordset.EOF Property
The EOF property returns a Boolean value indicating if the current record position is after the last record.
The EOF property returns a Boolean value that indicates if the current position in a Recordset object is just after the last record. If True, you are at EOF. If False, you are at or before the last record, but still inside the Recordset. The companion BOF property returns a Boolean value that indicates if the current position in a Recordset object is just before the first record. If both the BOF and EOF properties are True, then there are no records in the Recordset. If you are at EOF, then you should not call the MoveNext method. If you do, an error will be generated since there cannot be a next record.
Recordset.Filter Property
The Filter property sets or returns a variant value that is either a string, array of bookmarks, or a FilterGroupEnum value used to filter data. It can also use this property to turn an existing Filter off.
The Filter property sets or returns a variant value that can be a Criteria String, an array of bookmarks, or one of the FilterGroupEnum constants. The purpose of a filter is to allow you to select records that fit specific criteria that you have specified. Records that do not meet your criteria's are said to be filtered out. The Criteria String is composed of one or more clauses, where each clause has a FieldName, Operator, and a Value, in that order. Two or more clauses can be concatenated to each other using the AND or OR operators. The FieldName is the valid name of a field in a Recordset. If it contains any blank spaces, it must be enclosed inside a pair of square brackets (for example, [Last Name]). The Operator can only be one of the following: = < > <= >= <> LIKE If you use the LIKE operator, you can also use the * or % wildcards as the last character in the string or as the first and last character in the string.
39
The Value is the value that you want compared to the value in the field in the Recordset. It cannot be Null. Strings must be enclosed in a pair of single quotes (for example, 'DevGuru'). Dates must be enclosed in a pair of pound signs (for example, #12/25/2001#). Numbers can be preceded by a dollar sign (for example, $99.95). Also, the Filter property can set or return one of the FilterGroupEnum constants. A convenient way to determine if a filter is in effect is to test for adFilterNone. For a list of FilterGroupEnum constants see Table 28 on page 123
Recordset.LockType Property
The LockType property sets or returns a LockTypeEnum value that defines the type of locks that are in effect while editing records.
The LockType property sets or returns one of the LockTypeEnum constants that indicates the type of lock in effect on a record for editing. The default is read-only. You can only set this value when the Recordset is closed. Some providers do not support all of the lock types. If a provider does not support the requested value, it will substitute another value. After the Recordset is opened, you can return this property to determine the specific value being used. and the provider does not recognize this property, an error will be generated. For a list of LockTypeEnum constants see Table 29 on page 107
Recordset.MarshalOptions Property
The MarshalOptions property sets or returns a MarshalOptionEnum value that specifies which records are to be transferred (marshaled) back to the server.
The MarshalOptions property sets or returns one of the MarshalOptionsEnum constants that dictates whether all or just the modified records will be marshaled (transferred) from the client to the server. The default is to marshal all. For a list of MarshalOptionsEnum constants see Table 30 on page 107
Recordset.MaxRecords Property
The MaxRecords property sets or returns a long value that specifies the maximum number of records that can be returned to a Recordset object as the
40
result of a query.
The MaxRecords property sets or returns a long integer that dictates the maximum number of records that a query can return. This can be useful when you do not know how many records might be returned by a query to a very large database. The default is zero which signifies that there is no maximum limit. This value is passed to the provider and it is the responsibility of the provider to implement this limit. Note, this property has no effect on an Access database. You can only set this property when the Recordset is closed (read/write when closed, read-only when open). Not all providers recognize this property.
Recordset.PageCount Property
The PageCount property returns a long value that is the number of pages contained in a Recordset object.
After being called, this property will set the current record pointer to the first record on the last page. If the provider does not recognize this property, a value of -1 will be returned. You use the PageSize property to determine how many records will be displayed on each page.
Recordset.RecordCount Property
The RecordCount property returns a long value that is the count of how many records are in a Recordset object.
The RecordCount property returns a long value that is the number of records in the Recordset object. The Recordset must be open to use this property, otherwise a run-time error will be generated. If the provider does not support this property or the count cannot be done, a value of -1 will be returned. The type of cursor being used by the Recordset affects whether this property can return a valid count. In general, you can obtain the actual count for a keyset and static cursor. However, you may get either a -1 or the count if a dynamic cursor is being used, and you cannot get a count if a forward-only cursor is being used (-1 is returned).
41
Recordset.Sort Property
The Sort property sets or returns a string value that is a comma-delineated list of the names of which fields in the Recordset to sort.
After each name, you can optionally add a blank space and the keywords ASC or DESC to designate the sort direction. The Sort property sets or returns a string value that provides the names of the fields in the Recordset that you wish sorted. Each name must be separated by a delimiter comma and the entire string must be enclosed within a pair of double quotes. If the field name contains blank spaces, you need to enclose it within a pair of square brackets. You also have the option of specifying that the sort be in ascending or descending order for each individual field. You can declare the sort order by placing a blank space followed by either the keyword ASC, for an ascending sort, or DESC, for a descending sort, directly after the field name, but before the delimiter comma. The default is to sort in ascending order. Therefore, if you want an ascending sort, you could skip including the keyword ASC. The CursorLocation property will need to be set to adUseClient. When you are using a client-side cursor, the ADO Cursor Engine will automatically create a temporary index for the sort rather than physically rearranging the data. This makes the sort more efficient. You can also create your own temporary index by setting the Optimize property of the Properties Collection of the Field object to True. If you are using a server-side cursor, some providers may not support this property.
Recordset.Source Property
The Source property sets or returns a string value that defines the data source for a Recordset object.
The Source property can set either a string value or a Command object reference to specify a data source for a Recordset object, or it can return a string value that identifies the data source for a Recordset. You can only set the Source property if the Recordset object is closed. If the source is a Command object, then the ActiveConnection property of the Recordset object inherits the value of the ActiveConnection property of the Command object. The string can invoke an SQL statement, a stored procedure, or a table
42
name.
Recordset.State Property
The State property returns a long value describing if the Recordset object is open, closed, or in the process of connecting, executing, or retrieving.
The State property returns a long value that is the sum of one or more ObjectStateEnum constants. These constants describe if the Recordset object is open, closed, or executing an asynchronous operation. For a list of ObjectStateEnum constants see Table 5 on page 108
Recordset.Status Property
The Status property returns a sum of one or more RecordStatusEnum values describing the status of the current record..
Describe the status of the current record when it is subject to batch operations such as CancelBatch, Resync, or UpdateBatch. The string can invoke an SQL statement, a stored procedure, or a table name. For a list of RecordStatusEnum constants see Table 31 on page 124
Recordset.AddNew Method
The AddNew method used to create a new record. Syntax object.AddNew FieldList, Values Arguments Constant Description
The optional FieldList parameter is a variant that can be a single field name, or an array of field names, or the numeric (ordinal) position of the fields in the new record. For both the single name and array of names, each name must be enclosed within a pair of double quotes. Multiple names in the array must be separated (delimited) by commas. The optional Values parameter is a single value or an array of values for the fields that you want to populate in the new record. If the FieldList parameter is an array, then Values must also be an array. Further, Values must have the exact same number of members and be in the same order as FieldList.
FieldList
Values
43
The AddNew method is called to create and initialize a new record that can be added to an updateable Recordset. The provider must support adding new records. Since the parameters are optional, there are two ways to use the AddNew method, with or without the arguments. If you do not use parameters, then you will need to call the Update or UpdateBatch methods. When you use the optional parameters, ADO will automatically perform the update. However, if you are doing batch updates, you will still need to call the UpdateBatch method. Examples The Following code has 4 parts : Adding 1 new record Adding multiple records using arrays Add multiple/single record using variables Add multiple/single record without AddNew arguments
Option Explicit '--- Sample 1 oRst.AddNew "FirstName", "Dani" '--- Sample 2 oRst.AddNew Array("FirstName", "LastName"), Array("Dani", "Vainstein") '--- Sample 3 vFieldList = Array("FirstName", "LastName") vValues = Array("Dani", "Vainstein") oRst.AddNew varFieldList, varValues '--- Sample 4 oRst.AddNew oRst.Fields("FirstName") = "Dani" oRst.Fields("LastName") = "Vainstein" oRst.Fields("Age") = 37 oRst.Update
Recordset.Cancel Method
The Cancel method cancels the execution of a pending Open call. Syntax object.Cancel
The Cancel method is used to cancel the last pending, asynchronous call to the Open method of the Recordset object. An asynchronous call returns control to the calling program before the operation is completed and allows the execution of the code to continue.
44
Recordset.CancelBatch Method
The CancelBatch method used to cancel a pending batch update. You must be in batch update mode. Syntax object.CancelBatch AffectRecords Arguments Constant
AffectRecords
Description
The optional AffectRecords parameter is one of the AffectEnum constants that specifies which records are to be affected.
The CancelBatch method is called to cancel a pending batch update. The Recordset must be in batch update mode, otherwise an error will occur. Since you cannot predict what the current record will be after calling this property, you will need to move to a known record. For example, you could call the MoveFirst method, after the call to the CancelBatch method is completed. If the attempt to cancel the pending updates fails, the provider does not halt execution, but it will send warnings to the Errors Collection. Therefore you should always check the Errors Collection after the call to the CancelBatch method is completed. For a list of AffectEnum constants see Table 32 on page 124
Recordset.CancelUpdate Method
The CancelUpdate method used to cancel any changes made to the current row or to cancel the addition of a new row to a Recordset. This must be done before performing an Update. Syntax object.CancelUpdate
The CancelUpdate method is called to cancel any pending changes made to the current record including a newly added record. This can only be done before the Update method is called. Afterwards is too late since the record is saved and has become part of the database. The previous record will become the new current record.
Recordset.Clone Method
45
The CancelBatch method creates a duplicate copy of a Recordset object by copying an existing Recordset object.. Syntax object.Clone LockType Arguments Constant
LockType
Description
The optional LockType parameter is one of two possible LockTypeEnum constants. Note that there are actually five types of LockTypeEnum constants, but this method only recognizes two.
The Clone method allows you to create multiple copies, one at a time, of an existing Recordset object. In essence, this allows you to have two or more copies of a Recordset open for editing at the same time, unless you make the clones read-only. You do not actually make another physical copy which would require memory, but rather, you create a second (or third, etc.) pointer to the same Recordset. Since there is only one set of data, any changes made using either the original Recordset or one of the clones will be visible in the original and all clones. However, if you execute a Requery, you will lose synchronization. The provider, and hence the Recordset object, must support bookmarks or you cannot successfully create clones. You can use the same bookmark to find the same record in both the original and all clones. The current record is automatically set to the first record in a newly created clone. You must separately close the original and each clone. For a list of LockTypeEnum constants see Table 29 on page 123
Recordset.Close Method
The Close method is used to close a Recordset object. As a consequence, you also lose access to any associated data. Closing a Recordset object does not delete it from memory. You can later use the Open method to reopen the same Recordset, with or without the same properties. If you have closed an object and you no longer need it, you can set it equal to Nothing which will remove it from memory. Calling the Close method while an edit is in process will generate an error. You should first call the Update or CancelUpdate methods. If a Recordset is in batch update mode, you may need to call UpdateBatch before calling
46
Recordset.CompareBookmarks Method
The CompareBookmarks method Returns a CompareEnum value that compares the relative row position of two bookmarks in the same Recordset object. Syntax object.CompareBookmarks (Bookmark1, Bookmark2) Arguments Constant
Bookmark1 Bookmark2
Description
The Bookmark1 is the bookmark of the first record. The Bookmark2 is the bookmark of the second record.
The CompareBookmarks method returns one of the CompareEnum constants that allows you to compare the relative row positions of two records based upon the values of their bookmarks. Note that you are comparing bookmarks, not the values contained in the fields of the records. You can only make this comparison if both records are in the same Recordset object. You cannot compare bookmarks from two different Recordset objects. However, you can compare bookmarks for records in the same Recordset that have undergone sorting or filtering. Obviously, the provider must support bookmarks or you cannot use this method. For a list of CompareEnum constants see Table 33 on page 125
Recordset.Delete Method
The Delete method deletes the current record, a group of records, or all records. Syntax object.Delete AffectRecords Arguments Constant
AffectedRecords
Description
The Bookmark2 is the bookmark of the second record.
47
object for deletion. The Recordset must support deletions or an error will be generated. If you are in immediate update mode, the record will be immediately deleted from the database. If you are in client-side batch optimistic updating mode, the record will be removed from the Recordset, but it will not actually be deleted from the database until you call the UpdateBatch method. As long as the cursor is still on the current record that was marked for deletion, you can still access and manipulate that record. Once you move to another record, the deleted record is lost from the Recordset. However, you can cancel all types of pending changes, including deletions, by calling the CancelBatch method. One way to keep track of records being marked for a batch deletion is to collect and store the bookmark for each record before calling Delete. Another way is to set the Filter property to adFilterPendingRecords and to search for records with a Status property value of adRecDeleted. Attempting to access any of the fields of a record that has been deleted will generate an error.
Recordset.Find Method
The Find method Searches for a row in a Recordset that matches the given criteria. Syntax object.Find Criteria, SkipRecords, SearchDirection, Start Arguments Constant
Criteria
Description
The mandatory Criteria parameter is a string that defines the search criteria. This string must contain one field (column) name, one comparison operator, and a search value. The optional SkipRecords parameter is a long value that specifies how many records beyond the current record to skip to before starting the search. The default is zero which means that the search starts at the current record. The optional SearchDirection parameter is one of the SearchDirectionEnum constants that specify which direction the search should proceed, either forward or backward. If no matching record is found for a forward search, the record pointer is set at EOF. If no matching record is found for a backward search, the record pointer is set at BOF. The optional Start parameter is a variant that is either a bookmark or one of the BookmarkEnum constants that indicates the starting position for the search. The default is to start at the current record.
SkipRecords
SearchDirection
Start
The Find method is used to search a Recordset for a Record that matches the search criteria (a search string).
48
This method will work if the Recordset supports bookmarks. If the search is successful, the current record pointer will be moved to point to the first Record that matches. If the search fails, the Recordset will point to either EOF or BOF. You can only search on one field (column). The comparison operators in Criteria can only be one of the following = > >= < <= <> LIKE You cannot use OR or AND. The value in Criteria can be a date, number, or string. If the value is a string, it must be enclosed (delimited) within a pair of single quotes ("State = ' Tennessee' ") or a pair of pound signs ("State = #Tennessee# "). If the value is a date, it must be enclosed (delimited) within a pair of pound signs ("Birthdate = #6/26/1943# "). Numbers are not delimited ("Age = 104"). If you are using the LIKE operator, you can also use the asterisk * wildcard either after the value in Criteria or before and after the value in Criteria ( "LastName LIKE ' * stein * ' " or "State = ' T * ' ). Some providers also support using the % and _ wildcards. For a list of SearchDirectionEnum constants see Table 34 on page 125 For a list of BookmarkEnum constants see Table 35 on page 125
Recordset.GetRows Method
The GetRows method used to copy either all or a specified number of records into a two-dimensional array. Syntax object.GetRows Rows, Start, Fields Arguments Constant Description
The optional Rows parameter is one of the GetRowsOptionEnum constants which specify how many records to retrieve. Even if you request more records than are available in the Recordset, only the actual number of records will be returned and no error will be generated. The default is to select all records starting from the current record. The optional Start parameter is a variant that is either a bookmark or one of the BookmarkEnum constants that indicates the starting position for the search. The default is to start at the current record. The optional Fields parameter is a variant that can be a single field name, an ordinal position of a field, an array of field names, or an array of ordinal positions of the fields that you wish retrieved. It is used to restrict the fields that will be returned by calling this method. The order in which the field names are listed dictates the order in which they are returned.
Rows
Start
Fields
The GetRows method is used to copy records from a Recordset object into a variant that is a two-dimensional array. The variant array is automatically dimensioned (sized) to fit the requested number of columns and rows. To
49
allow backwards compatibility with earlier versions of ADO, the columns are placed in the first dimension of the array and the rows are placed in the second dimension. In comparison, the similar GetString method returns a specified Recordset as a string. For a list of GetRowsOptionEnum constants see Table 36 on page 125 For a list of BookmarkEnum constants see Table 35 on page 125
Recordset.GetString Method
The GetString method returns the specified Recordset as a string. Syntax object.GetString( StringFormat, NumRows, ColumnDelimiter, RowDelimiter, NullExpr) Arguments Constant
StringFormat
Description
The optional StringFormat parameter is one of the StringFormatEnum constants that define the format to be used when converting the Recordset object to a string. The optional NumRows parameter is a long value that specifies how many records in the Recordset to convert to a string. If left blank, the default is to do all of the records. If NumRows exceeds the actual number of available records, only the actual number will be returned and no error will be generated. The optional ColumnDelimiter parameter is a delimiter character used to space columns for ease of viewing and appearance. The default is the TAB character. To use this parameter, the StringFormat parameter must be set to adClipString. The optional RowDelimiter parameter is a delimiter character used to space rows for ease of viewing and appearance. The default is the CARRIAGE RETURN character. To use this parameter, the StringFormat parameter must be set to adClipString. The optional NullExpr parameter is an expression to use in place of Null. The default is the empty string "". To use this parameter, the StringFormat parameter must be set to adClipString.
NumRows
ColumnDelimiter
RowDelimiter
NullExpr
In comparison, the similar GetRows method returns a variant that is a twodimensional array containing selected records from a Recordset object. You cannot use this string to reopen the Recordset. For a list of StringFormatEnum constants see Table 37 on page 125
Recordset.Move Method
50
The Move method moves the position of the current record pointer. Syntax object.Move (NumRecords, Start) Arguments Constant
NumRecords
Description
The NumRecords parameter is a long value that specifies how many records the current record pointer will move. A value of zero does nothing. The optional Start parameter is a variant that is either a bookmark or one of the BookmarkEnum constants that indicates the starting position for the search. The default is to start at the current record.
Start
A positive number in parameter NumRecords, moves the current record pointer forward. If a forward move would take you past the last record, then the pointer is set to EOF and the EOF property is set to True. A negative number moves the current record pointer backwards. If a backward move would take you to before the first record, then the pointer is set to BOF and the BOF property is set to True. The Move method is called to move the position of the current record pointer. As required, the current cache of records is automatically updated in concert with the move. If the current record has been modified and an Update has not been performed, then when you call MoveFirst, there will also be an implicit call to Update for the current record. If you do not wish to keep the changes to the current record, then you should call CancelUpdate before you call MoveFirst. If a Recordset is using a forward moving cursor, then you can only go backwards as far as the first record in the current cache of records. Therefore, how far you can move backwards will be determined by the CacheSize property. However, you can go forward to as far as the last record or EOF. For a list of BookmarkEnum constants see Table 35 on page 125
Recordset.MoveFirst Method
The MoveFirst method moves the position of the current record pointer to the first record. Syntax object.MoveFirst
If the current record has been modified and an Update has not been performed, then when you call MoveFirst, there will also be an implicit call
51
to Update for the current record. If you do not wish to keep the changes to the current record, then you should call CancelUpdate before you call MoveFirst. If the Recordset is using a forward only cursor, it is possible that the provider will re-execute the command that originally created the Recordset which will automatically place the current record pointer to the first record. Potentially, this could be a very time-consuming process. This is one of four methods belonging to the Recordset object that allow you to navigate or move through a data record.
Recordset.MoveLast Method
The MoveLast method moves the position of the current record pointer to the last record. Syntax object.MoveLast
The MoveLast method is called to move to the last record in the specified Recordset object. If the Recordset does not support bookmarks and is using a forward only cursor, then an error will be generated when you call this method. If the current record has been modified and an Update has not been performed, then when you call MoveLast, there will also be an implicit call to Update for the current record. If you do not wish to keep the changes to the current record, then you should call CancelUpdate before you call MoveLast. This is one of four methods belonging to the Recordset object that allow you to navigate or move through a data record.
Recordset.MoveNext Method
The MoveNext method moves the position of the current record pointer forward to the next record. Syntax object.MoveNext
The MoveNext method is called to move to the next record in the specified Recordset object. If you are at the last record, calling this method will put you at EOF and the EOF property will be set to True. If you are at EOF and call this method, an error will be generated.
52
This is one of four methods belonging to the Recordset object that allow you to navigate or move through a data record.
Recordset.MovePrevious Method
The MovePrevious method moves the position of the current record pointer back to the previous record. Syntax object.MovePrevious
The MovePrevious method is called to move to the previous record in the specified Recordset object. If the Recordset does not support bookmarks and is using a forward only cursor, then an error will be generated when you call this method. If you are at the first record, calling this method will put you at BOF and the BOF property will be set to True. If you are at BOF and call this method, an error will be generated. This is one of four methods belonging to the Recordset object that allow you to navigate or move through a data record.
Recordset.NextRecordset Method
The NextRecordset method clears the current Recordset object and returns the next Recordset object. Syntax object.NextRecordset (RecordsAffected) Arguments Constant
RecordsAffected
Description
The optional RecordsAffected parameter is a long value returned by the provider that is the number of records affected by the current operation.
The NextRecordset method is called when you want to clear the current Recordset and return the next Recordset. The next Recordset object can be returned as: a closed Recordset with records. a closed non-row returning Recordset containing no records. an empty Recordset with both BOF and EOF equal to True. You should not call this method while the current Recordset is still being
53
edited. You can use this method to advance through a compound command statement or a stored procedure that needs to return multiple results. For example, in a compound command statement, ADO will process the first query and return the resultant Recordset. By calling the NextRecordset method, you can next process the second query (and so on). After all of the results are returned, the Recordset will be set to nothing.
Recordset.Open Method
The Open method opens a cursor that is used to navigate through records. Syntax object.Open ( Source, ActiveConnection, CursorType, LockType, Options) Arguments Constant Description
The optional Source parameter is a variant that can be any one of the following data sources: Source Command object SQL query string table name stored procedure call URL full or relative path/file name Stream object containing a Recordset
ActiveConnection
The optional ActiveConnection parameter is either a connection string that defines the connection, or it is a variant that contains the valid Connection object associated with the Recordset. If you pass a Command object in the Source parameter, you cannot use this parameter since the ActiveConnection property of the Command must already be set. The optional CursorType parameter is one of the CursorTypeEnum constants that specifies the type of cursor to use when you open a Recordset object. The optional LockType parameter is one of the LockTypeEnum constants that indicates the type of lock in effect on a Recordset. The default is adLockReadOnly. The optional Options parameter tells the provider how to evaluate the Source parameter when it contains something other than a Command object. The appropriate use of this option can speed up performance since ADO will not have to determine the type of the data source. It can be one or more of the following CommandTypeEnum or ExecuteOptionEnum constants.
CursorType
LockType
Options
54
gives you access to the records contained in the base table, the results from a query, or a previously saved Recordset. When you are done with the Recordset, you should call Close. For a list of CursorTypeEnum constants see Table 26 on page 122 For a list of LockTypeEnum constants see Table 29 on page 123 For a list of CommandTypeEnum constants see Table 7 on page 109 For a list of ExecuteOptionEnum constants see Table 6 on page 108
Recordset.Requery Method
The Requery method used to update (refresh) the data in a Recordset object. This is essentially equivalent to a Close followed by an Open. Syntax object.Requery (Options) Arguments Constant
Options
Description
The optional Options parameter is one of the ExecuteOptionEnum constants that specify how the provider is to execute a command (the requery).
The Requery method is called to update all of the records in an open Recordset by re-executing the query to the database that originally created the Recordset. If you need to change any of the property settings, you will have to call Close on the Recordset and then make the desired changes. This is because the properties are read-only when the Recordset is open and are read/write when the Recordset is closed. If you are in the process of adding a new record or editing the current record, an error will be generated if you call this method. If your database can be accessed by other users, it is quite possible that the new Recordset generated by the Requery will differ, perhaps significantly, from the previous Recordset. For a list of ExecuteOptionEnum constants see Table 6 on page 108
Recordset.Resync Method
The Resync method refreshes the data in the current Recordset object by resynchronizing records with the underlying (original) database. Syntax object.Resync (AffectRecords, ResyncValues)
55
Arguments Constant
AffectRecords
Description
The optional AffectRecords parameter is one of the AffectEnum constants that specifies which records are to be affected. The default is adAffectAll. The optional ResyncValues parameter is one of the ResyncEnum constants that determines which values can be overwritten. The default is adResyncAllValues.
ResyncValues
The Resync method is used to re-fetch the data from the underlying data source and to update (resynchronize) the values in the current Recordset. Since this is not a re-query, new records in the database will not be added to the Recordset. If you call this method on a server-side Recordset, you will get an error. Likewise, you cannot use this method on client-side, read-only Recordset objects. If the call to this method fails because of conflicts with the underlying date (such as a record having been deleted), warnings will be returned to the Errors Collection and a run-time error will be generated. For a list of AffectEnum constants see Table 32 on page 124 For a list of ResyncEnum constants see Table 19 on page 120
Recordset.Save Method
The Save method saves the Recordset to a file or Stream object. Syntax object.Save (Destination, PersistFormat) Arguments Constant
Destination
Description
The optional Destination parameter is a variant that is either a string that contains the complete path to the file where you want the Recordset object to be saved, or is a reference to a Stream object. The optional PersistFormat parameter is one of the PersistFormatEnum constants that specify the format, either ADTG or XML, in which to save the Recordset.
PersistFormat
You can only call this method on an open Recordset. After the save is complete, the Recordset will still be open and the current record pointer will be on the first record. If any asynchronous operation is occurring, such as a fetch or update, this method will wait until the operation is completed before performing the save.
56
If a filter is in place, only the visible records are saved. You have the option of declaring this parameter the first time you save a specific Recordset. When you subsequently resave the same Recordset, this method will automatically save that Recordset to the same location without you having to re-declare this parameter. In fact, if you do redeclare the same value for this parameter, you will get an error. If you do not specify a Destination, the new file will be set to the path/name value of the Source property of the Recordset object being saved. Of course, you can save the Recordset to a new location by using this parameter any time after the first save. Note that you will end up with two open Recordset objects, each at a different location. For a list of PersistFormatEnum constants see Table 10 on page 112
Recordset.Seek Method
The Seek method uses the index of a Recordset to locate a specified row. Syntax object.Seek (KeyValues, SeekOption) Arguments Constant
KeyValues SeekOption
Description
The KeyValues parameter is a variant array that contains one or more values to compare against the values in each corresponding column. The SeekOption parameter is one of the SeekEnum constants that specify how to conduct the search. The default is adSeekFirstEQ.
The Seek method uses the provider to search using indexes to find a Record in a Recordset that matches the values specified in the KeyValues parameter. If a match occurs, the current record pointer will point to the matching record or where specified by the SeekOption parameter. If no match occurs, the current record pointer will be placed at the end of the Recordset. Very few providers support this method. The provider must support this method and the use of indexes on the Recordset (see the Index property). This method can only be used with server-side cursors. For a list of SeekEnum constants Table 38 on page 126
Recordset.Supports Method
The Suports method returns a Boolean value that indicates whether or not a Recordset object will support a specific type of functionality. Syntax
57
Description
The CursorOptions parameter is a long expression that is composed of one or more CursorOptionEnum constants. There is no default value. These values can be joined together in this parameter using a Boolean logic operator such as an OR.
The Supports method returns a Boolean value that indicates whether or not the specified functionality will be supported by the Recordset object. A return of True means that the functionality is supported. While False means that the functionality is not supported. The Recordset object that you have opened, and the provider that you are working with, simply may not support using all of the various events, methods, and properties that are potentially available to the Recordset object. Further, even if a True is returned by this method, the provider still may not support the functionality under all possible circumstances. For a list of CursorOptionEnum constants Table 39 on page 126
Recordset.Update Method
The Update method used to save any changes made to the current row of a Recordset object. Syntax object.Update (Fields, Values) Arguments Constant
Fields Values
Description
The optional Fields parameter is a variant that is either a single field name, or an array of field names or ordinal positions, that you want to update. The optional Values parameter is a variant that is a value or array of values for the field or array of fields that you wish to update.
The Update method is called to save all changes you have made to the current Record to both the Recordset object and the data source. Clearly, both the Recordset object and the data source must support updates. If you have made changes to a record and then move to another record, the Update method is implicitly called and the record is saved. After a call to this method is completed, the current record pointer will still point to the same current record. The Update method is used to save a single record. The UpdateBatch method is called to save multiple records. (If the
58
Recordset object supports batch updating, the new and changed records will be locally cached until you call the UpdateBatch method.)
Recordset.UpdateBatch Method
The UpdateBatch method Writes all pending batch updates to the underlying database. Syntax object.Supports (AffectRecords) Arguments Constant
AffectRecords
Description
The optional AffectRecords parameter is one of the AffectEnum constants that specifies which records are to be affected.
The UpdateBatch method is called to save to the data source all of the pending changes and additions that have occurred in a Recordset object since the last update. Clearly, the Recordset must support batch updating. When a Recordset is in batch updating mode, all of the changes and new additions are saved in a local cache until the BatchUpdate method is called. (The LockType property of the Recordset object must return the adLockBatchOptimistic constant which specifies that multiple users can modify the data and that all changes are locally cached.) If all or part of the UpdateBatch fails, a warning is returned to the Errors Collection and an error is generated. You can cancel a BatchUpdate by calling the CancelBatch method. For a list of AffectEnum constants Table 32 on page 124
59
Stream.Charset Property
The Charset property sets or returns a string value that specifies into which character set the contents of a text Stream are to be translated.
The CharSet property sets or returns a string value that specifies into which character set the text data will be translated by ADO. This property is not used with binary data. The default character set is the Unicode format. Also, regardless of what character set is specified by CharSet, the data is always stored in the Unicode format inside the Stream object. The wisest course of action is to set the CharSet property before the Stream is opened. However, if the Stream is already open, you can set the CharSet property without ill effects only if the Position property of the Stream object is set to zero (which marks the beginning of the text data).
Stream.EOS Property
The EOS property returns a Boolean value indicating whether or not the current position is at the end of the stream.
The EOS property returns a Boolean value that indicates whether or not you are at the end of the stream. If True, you are at the end. If False, you are not at the end and additional bytes of data remain in the Stream beyond the current position. You can determine your current position using the Position property and you can call the SetEOS method to designate the current position as the end of the stream.
60
Stream.LineSeparator Property
The LineSeparator property sets or returns a LineSeparatorEnum value that specifies which binary character to use as the line separator in a text Stream object.
The LineSeparator property sets or returns a LineSeparatorEnum constant that dictates which type of line separator character will be used when reading the text data of a Stream. If you try to use this property with binary data, nothing will happen. For a list of LineSeparatorEnum constants see Table 40 on page 126
Stream.Mode Property
The Mode property sets or returns a ConnectModeEnum value that specifies the available permissions for modifying data.
The Mode property sets or returns a ConnectModeEnum constant that dictates the access permissions for a Stream object. If the access mode is not set, it will be inherited from the source that is used to open the Stream. There are two possible default values for this property. The default for a Stream associated with an underlying data source is adReadOnly. While the default for a Stream that is not associated with an underlying data source is adModeUnknown. This property is read-only if the Stream object is open and read/write if closed. For a list of ConnectModeEnum constants see Table 4 on page 108
Stream.Position Property
The Position property sets or returns a Long value that specifies the current position, measured in bytes, from the beginning of the stream.
The Position property sets or returns a long value that is the number of bytes from the start of the data to the current position inside the Stream object. The start position is defined as zero. You cannot set this property using a negative number. If the Stream is read-only and you specify a Position that is greater than the actual size of the data, ADO will neither return an error nor modify the contents or size of the Stream. However, if the Stream is read/write and
61
you specify a Position that is greater than the actual size of the data, ADO will increase the size of the Stream object to the new, larger number of bytes and will insert null values to pad the data.
Stream.Size Property
The Size property returns a long value that is the size in bytes of an opened Stream object.
Note that this property requires that the Stream be open. If it is not open, an error will be generated. If the size is not known, the return value is -1. If the size exceeds the upper limit of a long value, a truncated size is returned.
Stream.State Property
The State property returns a long value describing if the Stream object is open or closed.
The State property returns a long value that is the sum of one or more ObjectStateEnum constants. These constants describe if the Stream object is open or closed. The default value is adStateClosed. You can call the State property at any time. For a list of ObjectStateEnum constants see Table 5 on page 108
Stream.Type Property
The Type property sets or returns a StreamTypeEnum value defining if the data is binary or text.
The default is text. However, when binary data is written to a new, empty Stream object, the Type will be implicitly set to binary. You can set this property for a Stream object if it is open or closed, but if the object is open, the Position must be set to zero (the start of the stream). If the object is open and the Position is not at zero, this property is read-only (return). For text data, the character set used for translation is set using the CharSet property. For a list of StreamTypeEnum constants see Table 41 on page 126
62
Stream.Cancel Method
The Cancel method cancels the execution of a pending Open call. Syntax object.Cancel
The Cancel method is used to cancel the last pending, asynchronous call to the Open method of the Stream object. An asynchronous call returns control to the calling program before the operation is completed and allows the execution of the code to continue.
Stream.Close Method
The Close method is used to close a Stream object. As a consequence, you also lose access to any associated data. Closing a Stream object does not delete it from memory. You can later use the Open method to reopen the same Record, with or without the same properties. If you have closed an object and you no longer need it, you can set it equal to Nothing which will remove it from memory.
Stream.CopyTo Method
The CopyTo method copies the specified number of characters or bytes from one Stream object to another Stream object. Syntax object.CopyTo (DestStream, NumChars) Arguments Constant
DestStream
Description
The mandatory DestStream parameter is a reference to an open Stream object that is the destination. The destination Stream object must not be a proxy of the source Stream object.
63
NumChars
The optional NumChars parameter is a long integer that is either the number of characters of text data or the number of bytes of binary data to be copied from the current position in the Stream. If the specified number is greater than the actual number of bytes or characters available from the current position to EOS in the source Stream, then only the available number of bytes or characters will be copied and no error will be generated. If this parameter is left blank or set to -1, the default is to copy all data from the current position to EOS.
The CopyTo method is used to copy binary or text data from a source Stream object into a destination Stream object. Both Stream objects must be open or an error will be generated. Ideally, the type (text or binary) of both the source and destination Stream objects should be the same. However, you can copy a text Stream object into a binary Stream object, but not vise-versa. The default is to copy all data from the current position to the end of the stream (EOS). If there is existing data in the destination Stream object, it may not necessarily be completely overwritten during the copy. If the source copy data is smaller in size than the existing data at the destination, then the existing data that extends beyond the end of the copy will not be overwritten and will remain in the destination Stream. This method has one mandatory and one optional parameter. You can set the CharSet property of the destination Stream object to be different than the source and the text will be appropriately translated.
Stream.Flush Method
The Flush method sends the contents of the Stream object to the underlying object that is the source of the Stream object. Syntax object.Flush
The Flush property is called when you need to send the data buffered in the Stream object to the associated underlying object. This will ensure that the contents have been written. Since ADO continually flushes the buffer, you should rarely need to call Flush. For example, when you call Close, there is an implicit flush.
Stream.LoadFromFile Method
The LoadFromFile method loads the contents of an existing file into an open Stream object. Syntax
64
Description
The FileName parameter is a string that is the name of the file (including the path, if needed) to be loaded. This file must already exist, or an error will occur.
The LoadFromFile method is used to load the contents of a local file into an open Stream object. All existing data in the Stream object will be completely overwritten, and hence, will be lost. The position will also be set to zero, the start of the data.
Stream.Open Method
The Open method opens a Stream object from a URL or Record object. Syntax object.Open (Source, Mode, OpenOptions, UserName, Password) Arguments Constant Description
The optional Source parameter is a variant that indicates the source of the data for the Stream object. This can be a URL or a reference to an already opened Record object. If you do not specify a source, a new Stream will be created and opened. It will have a Size of zero and will contain no data since it will not be associated with any underlying source. The optional Mode parameter is one of the ConnectModeEnum constants that dictate the access permissions for a Stream object. If the Source parameter is an already opened Record object, this parameter will be implicitly set. The optional OpenOptions parameter is a StreamOpenOptionsEnum constant that specifies possible options for opening a Stream object. The optional UserName parameter is a string containing the name of a user who can access the Stream object. If the Source parameter is an already opened Record, neither the UserName nor the Password parameter is used. The optional Password parameter is a string containing the password that validates the UserName parameter. If the Source parameter is an already opened Record, neither the UserName nor the Password parameter is used.
Source
Mode
OpenOptions
UserName
Password
The Open method is called to open a Stream object. While the Open operation is occurring, you temporarily cannot set any properties until the open is completed. Remember, prior to opening a Stream, you can access
65
the various read-only properties and obtain values. For a list of ConnectModeEnum constants Table 4 on page 108 For a list of StreamOpenOptionsEnum constants see Table 42 on page 127
Stream.Read Method
The Read method reads the specified number of bytes from a binary Stream object and returns the data as a variant. Syntax object.Read (NumBytes) Arguments Constant Description
The optional NumBytes parameter is either the number of bytes to read or one of the StreamReadEnum constants. If you specify a number larger than the actual number of bytes available in the Stream, only the actual available bytes are read and no error is generated. A null value is returned if there are no bytes left to be read.
NumBytes
The Read method is used to read an entire binary file or a specified number of bytes from a Stream object and to return the data as a variant. This method is used exclusively for binary data type Stream objects. Please use the similar ReadText method for text data type Stream objects. For a list of StreamReadEnum constants see Table 43 on page 127
Stream.SaveToFile Method
The SaveToFile method copies (saves) the contents of an opened Stream object to a specified file. Syntax object.SaveToFile (FileName, SaveOptions) Arguments Constant
FileName
Description
The FileName parameter is a string that is the name of the file (including the path, if needed) into which the data will be saved. This can be the name of an existing file or a new file you wish to create. The optional SaveOptions parameter is one of the SaveOptionsEnum constants that allow you to either overwrite an existing file or create a new file. If left blank, the default is to create a new file.
SaveOptions
66
The SaveToFile method can be called when you want to save the binary contents of a Stream object to a local file. This can be an already existing file or a newly created file. After the save is accomplished, the position will be set to zero. If you save to an existing file, all existing bytes contained in the file will be completely overwritten. This method does not change or affect the Stream object in any way. There is one mandatory and one optional parameter. For a list of SaveOptionsEnum constants see Table 44 on page 127
Stream.SetEOS Method
The SetEOS method sets the value of the EOS property to be the current position. Syntax object.SetEOS
The SetEOS method is used to set the current position to be the end of the stream (EOS). If any data exists beyond the newly set EOS, it will be truncated and permanently lost. Remember that you can use the Position property to set the position in the data. Also, the CopyTo, Write, and WriteText properties do not truncate.
Stream.SkipLine Method
The SkipLine method skips all of the characters on one entire line, including the next line separator, while reading a text stream. Syntax object.SkipLine
The SkipLine method is used to skip over all characters up to and including the next line separator in a text data Stream object. If there is no line separator between the current position and EOS, the new current position simply becomes the EOS. By default, this method searches for an adCRLF line separator which is a carriage return/line feed. You can use the LineSeparator property to set or return a LineSeparatorEnum value that specifies which binary character to use as the line separator in a text Stream object. For a list of LineSeparatorEnum constants Table 40 on page 126
67
Stream.Write Method
The Write method writes a specified number of bytes of binary data to an opened Stream object without adding any intervening spaces. Syntax object.SaveToFile (Buffer) Arguments Constant
Buffer
Description
The Buffer parameter is a variant that contains the binary data to write to the Stream.
The Write method can be used to append or add binary data to a Stream object. To add text data, use the similar WriteText method. If there already is binary data (bytes) in the Stream object and the current position is set to EOS, the new binary data will be appended onto the end of the existing data. However, if the current position is not at EOS, then the existing data will be overwritten. If you write past the current EOS, the size of the Stream will be implicitly increased, the new EOS will become the last byte in the Stream; and the current position will be set at EOS. If you do not write past the current EOS, the current position will be set at the next byte after the newly written data. You will also be left with truncated, previously existing data starting at the new current position and continuing out to EOS. You can call the SetEOS method to truncate.
Stream.WriteText Method
The WriteText method writes a specified text string to an opened Stream object without adding any intervening spaces or characters. Syntax object.WriteText (Data, Options) Arguments Constant
Data
Description
The Data parameter is a string that contains the text data to write to the Stream. The Options parameter is one of the StreamWriteEnum constants that determines whether or not a line separator is added to the end of the written text. The LineSeparator property must be set if you wish to add a line separator, or a run-time error will occur.
Options
68
The WriteText method can be used to append or add text data to a Stream object. To add binary data, use the similar Write method. If there already is text data (characters) in the Stream object and the current position is set to EOS, the new text data will be appended onto the end of the existing data. However, if the current position is not at EOS, then the previously existing data will be overwritten. If you write past the current EOS, the size of the Stream will be implicitly increased, the new EOS will become the last character in the Stream; and the current position will be set at EOS. If you do not write past the current EOS, the current position will be set at the next character after the newly written data. You will also be left with truncated, previously existing data starting at the new current position and continuing out to EOS. You can call the SetEOS method to truncate.
69
The Count property returns a long value that is the number of items in the collection. The counting starts at zero. You can use this value to loop through the collection by iterating from zero to the value of Count minus one.
Use the Count property to determine how many objects are in a given collection Because numbering for members of a collection begins with zero, you should always code loops starting with the zero member and ending with the value of the Count property minus 1. Up with two open Recordset objects, each at a different location. If you want to loop through the members of a collection without checking the Count property, use the For Each...Next statement. If the Count property is zero, there are no objects in the collection. You can also use the For Each ... Next statement.
Errors.Item Property
The Item property is used to return a specific member of the Errors Collection. Syntax object.Item (nIndex)
The nIndex parameter is the position (ordinal) number. You can retrieve the value of an item in the collection using the following methods
Set oError = objConnection.Errors.Item(5) Or: Set oError = objConnection.Errors(5)
Errors.Clear Method
The Clear method removes all of the objects in a collection. Syntax object.Clear
Use the Clear method on the Errors collection to remove all existing Error objects from the collection. When an error occurs, ADO automatically clears the Errors collection and fills it with Error objects based on the new error. Some properties and methods return warnings that appear as Error objects in the Errors collection but do not halt a program's execution. Before you call the Resync, UpdateBatch, or CancelBatch methods on a
70
Recordset object; the Open method on a Connection object; or set the Filter property on a Recordset object, call the Clear method on the Errors collection. That way, you can read the Count property of the Errors collection to test for returned warnings.
Errors.Refresh Method
The Refresh method updates the objects in the Collection Syntax object.Refresh
The Refresh method updates the Property objects in the Properties Collection with the dynamic property information specific to the provider. It is quite possible that the provider has dynamic properties that are not supported by ADO.
The Description property returns a string that describes the error. This is the default property.
The Description property returns a string that is a brief textual description of the error. This is the default property for the Error object. Since both the provider and ADO can generate errors, either may be the source of the error.
71
It is the responsibility of the provider to pass error information, including the description string, to ADO. When an error does occur, it is the responsibility of ADO to create an Error object, which contains all of the error information, and to add that object to the Errors Collection. Example The Following code implements a subroutine to report one or more errors when using ADODB.
Public Sub ReportDBError(ByVal oConn) Dim sErrInfo For Each oError in oConn.Errors sErrInfo = "Description: " & oError.Description & vbNewLine & _ "Help Context: " & oError.HelpContext & vbNewLine & _ "Help File: " & oError.HelpFile & vbNewLine & _ "Native Error: " & oError.NativeError & vbNewLine & _ "Number: " & oError.Number & vbNewLine & _ "Source: " & oError.Source & vbNewLine & _ "SQL State: " & oError.SQLState & vbNewLine Reporter.ReportEvent micWarning, "DB Error", sErrInfo Next oConn.Errors.Clear End Sub
Error.HelpContext Property
The HelpContext property returns a long value that is the context ID in the help file (if it exists) for the error.
The HelpContext property returns a long value that is the context ID of a topic in a Windows help system. The companion HelpFile property returns a string that is the path and file name of the help file in a Windows help system. Both of these properties allow you to interact with the Microsoft Windows help system. This involves calling the Windows API Help functions. If you do not have such access, the HelpContext property returns zero and the HelpFile property returns the empty string "".
Error.HelpFile Property
The HelpFile property returns a string that is the path and name of the help file (if it exists).
The HelpFile property returns a string that is the path and file name of the help file in a Windows help system.
72
The companion HelpContext property returns a long value that is the context ID of a topic in a Windows help system. Both of these properties allow you to interact with the Microsoft Windows help system. This involves calling the Windows API Help functions. If you do not have such access, the HelpContext property returns zero and the HelpFile property returns the empty string "".
Error.NativeError Property
The NativeError property returns a long value that is the database error information for a specific Error object.
The NativeError property is a long value that is an error code that is returned to ADO by the data source or the provider when an error occurs. ADO uses the NativeError property to allow access to this underlying error code. You will have to refer to the data source/provider documentation for an explanation of the returned error code.
Error.Number Property
The Number property returns a long value that is the unique number that identifies an Error object.
The Number property returns a long value that should correspond to one of the ErrorValueEnum constants, which are unique ADO numbers that describe the error being reported. The numbers can be a positive decimal, a negative decimal, or a hexadecimal value, and are equivalent to the Windows API HRESULTS values. For a warning, the number property will be zero. Remember that errors are reported by ADO, but that they can be generated by either ADO or the underlying provider (data source). If the error was generated by the provider, the Number property may be set to an unspecific error value, such as: -2147217900 or -2147467259 For a list of ErrorValueEnum Values see Table 11 on page 116
Error.Source Property
The Source property returns a string that is the name or ID of the object or application that generated the error.
73
The Source property returns a string value that is the name of the object or application that generated the error. Remember that errors can be generated by both ADO and the underlying data source (provider). For ADO, the returned value will be of the format "ADO.oName" where oName is the name of the object that originated the error.
Error.SQLState Property
The SQLState property Returns a five character string that is the SQL error code.
The SQLState property is a string that contains the five-character SQL error code that is returned by the provider when an error occurs during the execution of an SQL command (query). The SQL error codes are supposed to follow at least the minimum standards established by the "SQL Access Group." However, providers can vary greatly as to which portions of the SQL standards they recognize. You will need to consult the SQL documentation that is usually available from the provider in order to interpret the error code. Some SQL errors may not have a code and the returned value will be blank.
74
The Count property returns a long value that is the number of items in the collection
Use the Count property to determine how many objects are in a given collection Because numbering for members of a collection begins with zero, you should always code loops starting with the zero member and ending with the value of the Count property minus 1. If you want to loop through the members of a collection without checking the Count property, use the For Each...Next statement. If the Count property is zero, there are no objects in the collection.
Fields.Append Method
The Append method is used to add (append) a Field object to the Fields Collection. Syntax object.Append (Name, Type, DefinedSize, Attrib, FieldValue) Arguments Constant
Name Type
Description
Optional. Unique name of the new Field object being appended to the collection. Optional. One of the DataTypeEnum constants that defines the data type of the new Field. Optional. long value that is the size in bytes or characters of the new Field. When DefinedSize exceeds 255 bytes, the field is treated as having variable length columns. Optional. One of the FieldAttributeEnum constants that specify the attributes of the new Field. Optional. A variant that is the value for the new Field. If this parameter is not provided, it will be set to null when the new Field is appended.
DefinedSize
Attrib
FieldValue
Using this method, you can both append and assign a value to the object at the same time. This is useful, because the Value property must first be set and an Update must have occurred, before you can set any other
75
properties. There are three data types for the Field object that cannot be appended to the Fields Collection. If you try to use adArray, adChapter, or adEmpty, an error will occur. For a list of DataTypeEnum Values see Table 12 on page 117 For a list of FieldAttributeEnum Values see Table 15 on page 118
Fields.CancelUpdate Method
The CancelUpdate method cancels all pending deletions, insertions, or updates to the Fields Collection for a specific Record object. Syntax object.CancelUpdate
All existing Field objects are returned to the value they had after the last call of the Update method (if a call occurred). The status value is set to adFieldOK for all Field objects in the collection. This method has no parameters. For a list of FieldStatusEnum Values see Table 18 on page 120
Fields.Delete Method
The Delete method designates that a specified Field object is to be deleted from the Fields Collection. Syntax object.Delete (Name, Type, DefinedSize, Attrib, FieldValue) Syntax Constant
Index
Description
The Index parameter is either the name property or the ordinal position (index) in the collection of the Field object.
This Index parameter can be the name of the Field object or the ordinal position of the Field object itself. You must call the Update method of the Fields Collection to make this deletion.
Fields.Refresh Method
76
The Refresh method used to update objects in a collection, this method has no effect on the Fields Collection of the Record object. Syntax object.Refresh
Using the Refresh method on the Fields collection has no visible effect. To retrieve changes from the underlying database structure, you must use either the Requery method or, if the Recordset object does not support bookmarks, the MoveFirst method.
Fields.Resync Method
The Resync method is used to re-fetch the data from the underlying data source and to update (resynchronize) the values in the OriginalValue, UnderlyingValue, and Value properties of Field objects that are in the Fields Collection object of a Record object, or just to update the UnderlyingValue property. Syntax object.Resync
Use the Resync method to resynchronize the values of the Fields collection of a Record object with the underlying data source. The Count property is not affected by this method. The effect of calling this method will depend on the value of the Status for each Field object. Resync will not modify Status values of Field objects unless an error occurs when Resync is called. For example, if the field no longer exists, the provider will return an appropriate Status value for the Field object, such as adFieldDoesNotExist. Returned Status values may be logically combined within the value of the Status property. For a list of ResyncEnum Values see Table 19 on page 120
Fields.Update Method
The Update method is called to make additions, deletions, and updates to the Fields Collection of the Record object. Syntax object.Update
77
The Update method finalizes additions, deletions, and updates to fields in the Fields collection of a Record object. For example, fields deleted with the Delete method are marked for deletion immediately but remain in the collection. The Update method must be called to actually delete these fields from the provider's collection.
The ActualSize property returns a long value that is the actual length of a Field object's value.
The ActualSize property sets or returns a long value that is the actual length of a Field object value. If ADO cannot determine the length, this property will return adUnknown. The companion property, DefinedSize, is used to set the maximum size of a value In other words, DefinedSize defines how long a value can be, while ActualSize telling how long it really is.
Field.Attributes Property
The Attributes property returns a long value that is the sum of one or more FieldAttributeEnum values that define the characteristics of a Field object.
The Attributes property returns a long value that is the sum of one or more FieldAttributeEnum constants that indicate the characteristics of a Field object. The default is zero. The Attributes property has read/write permission when being used to create recordsets, but converts to read-only when you open an already created recordset. Not all providers support this property.
78
Field.DefinedSize Property
The DefinedSize property returns a long value that is the defined (maximum possible) size (data capacity) of a Field object.
The DefinedSize property returns a long value that is the defined or maximum size in bytes of a Field object. Size can also be referred to as data capacity. The DefinedSize property has read/write permission when being used to create recordsets, but converts to read-only when you open an already created recordset. The companion ActualSize property sets or returns a long value that is the actual length of a Field object value. In other words, DefinedSize defines how long a value can be, while ActualSize telling how long it really is.
Field.Name Property
The Name property sets or returns a string value that is the name of the Field object.
The Name property returns a string that is the name of a Field object. For example, you can use this property when adding a Field object to a Fields Collection or to a Recordset object. This property has read/write permission when being used to create recordsets, but converts to read-only when you open an already created recordset. The name can be obtained from the Fields Collection (see example) and the Properties Collection. The Name property is also used by the Command, Parameter, and Property objects.
Field.NumericScale Property
The NumericScale property sets or returns a byte value that is the number of digits allowed to the right of the decimal point for a numeric Field object.
The NumericScale property returns a byte value that defines how many digits are stored to the right side of the decimal point for a numeric value (number) of a Field object. The number of digits stored on the right side is also referred to as the scale
79
of the number. The NumericScale property has read/write permission when being used to create recordsets, but converts to read-only when you open an already created recordset.
Field.OriginalValue Property
The OriginalValue property returns a variant that is the value of a field in the database before any changes made in the current session.
The OriginalValue property returns a variant that is the value of the Field object as it existed in the record after the last Update or UpdateBatch method call, but before any current changes. This is possible because additions and deletions to the Field are cached until an update is performed. This is a quick way to get back to the original Field value. Calling either the CancelBatch or CancelUpdate methods of the Recordset object will have the same effect as calling the OriginalValue property. The provider will return the value that the Field had after the last Update or UpdateBatch method call, but prior to any current changes.
Field.Precision Property
The Precision property sets or returns a byte value that is the maximum number of digits allowed in a numeric Field object.
The Precision property sets or returns a byte value that defines the maximum number of digits that a number (numeric value) can have in a Field object. This maximum number is also referred to as the degree of precision. Normally, Precision is read-only for a Field object. However, after the Value has been set for the Field object and after a subsequent Update method call for a Fields collection, it can become read/write.
Field.Status Property
The Status property returns a FieldStatusEnum value that allows you to determine if a field has been successfully added.
The Status property returns a FieldStatusEnum value that describes the current status of a Field object. The default is adFieldOK.
80
Pending updates, such as additions and deletions to the Fields Collection, are cached until the Update method of the Record object is called. The Status property allows you to find out if any pending updates have been done and whether or not the attempt was successful. If the update failed, an error is returned and is combined with the FieldStatusEnum value. The combined value is returned by the Status property. With ADO 2.6 the Status property is now filled with information to help with the 'Errors Ocurred' error. For a list of FieldStatusEnum Values see Table 18 on page 120
Field.Type Property
The Type property Sets or returns a DataTypeEnum value that specifies the data type.
The Type property sets or returns a DataTypeEnum value which is the data type or operational type of the Field object. This property becomes read/write after the value has been set and the object has been added to the Fields Collection. Otherwise it is read-only. Unfortunately, some providers may not support all of the possible data types. If a provider encounters a data type that it does not recognize, it will usually change it to a data type that it does recognize. For a list of DataTypeEnum Values see Table 12 on page 117
Field.UnderlyingValue Property
The UnderlyingValue property returns a variant that is the current field value as stored in the database.
The UnderlyingValue property returns a variant that is the current value of the Field object as stored in the cursor. It is referred to as the underlying value, because the value you are viewing may not necessarily show changes made by other users and may not be the latest value. The value returned by the UnderlyingValue property will reflect all of the changes made in the current record for the specified Field. This can be very useful for resolving conflicts between changes made by you and other users. You can also use the Resync property of the Recordset object to get the latest values for all of the Field objects in the Fields Collection. If you need the original value, you can obtain it by using the
81
OriginalValue property.
Field.Value Property
The Value property returns a variant that is the current (visible) field value in the current Recordset.
The Value property sets or returns a variant that is the current value of the Field object. It may not be the same as the original value, the underlying value, or the value stored in the database. You can obtain the underlying value using the UnderlyingValue property. You can obtain the original value using the property. After a new Field object has been added to the Fields Collection, you must first set the Value property and perform an update before you can set any other property.
Field.AppendChunk Method
The Value method is used to append a large amount (i.e., a large chunk) of text or binary data to a Field object. Syntax object.AppendChunk (Data) Arguments Constant
Data
Description
A variant that is the binary or text data that you want to add to the Field object.
This method and the companion GetChunk method allow you to manipulate databases that contain, for example, large text files or images. The first time that you call AppendChunk, the data is not appended, but rather, it overwrites any existing data in the Field object. The second time that you call AppendChunk, the data is appended to the existing data. All subsequent calls will also append the data. However, if you set or read the value of another Field, then go back to the first Field, and call AppendChunk, the call will be treated as a first call and the data will overwrite rather than being appended. You can use this method to pass large amounts of data into a Field object in reasonable sized blocks.
82
Field.GetChunk Method
The GetChunk method returns a variant that contains the specified amount (size) of binary or text data. Syntax object.GetChunk (Size) Arguments Constant
Size
Description
A variant that is the binary or text data that you want to add to the Field object.
The GetChunk method returns all or a portion of a binary or text data contained in a Field object. To use the GetChunk method, the adFldLong constant of the Attributes property of the specified Field object must be set to True. This method and the companion AppendChunk method allow you to manipulate databases that contain, for example, large text files or images. You can use this method to retrieve reasonable sized chunks of data from a Field object. The first GetChunk call will retrieve data starting at the beginning of the file. Each subsequent call proceeds from the point that the previous call ended. However, if you set or read the value of another Field, then go back to the first Field, and call GetChunk, this call will be treated as a first call and will retrieve data starting at the beginning of the file. A null will be returned if the Field is empty. If there is no record, you will get an error.
83
If the provider will allow, you can populate the Parameters Collection by using the Refresh method. In fact, if you try to access this collection while it is empty or before you have called Refresh for the first time, ADO will automatically call Refresh to populate the collection. It is more efficient to provide the parameters, rather than having to call and obtain this information from the provider. (Anything you can do to reduce calls to the provider will improve performance.) You can add Parameter objects using the Append property. The collection starts numbering (indexing) with the number zero.
The Count property returns a long value that is the number of items in the collection. The counting starts at zero. You can use this value to loop through the collection by iterating from zero to the value of Count minus one.
Use the Count property to determine how many objects are in a given collection Because numbering for members of a collection begins with zero, you should always code loops starting with the zero member and ending with the value of the Count property minus 1. If you want to loop through the members of a collection without checking the Count property, use the For Each...Next statement. If the Count property is zero, there are no objects in the collection.
Parameters.Item Property
The Item property is used to return a specific member of the Parameters Collection.
Parameters.Append Method
The Append method is used to add (append) a Parameter object to the Parameters Collection. Syntax object.Append (Object) Arguments
84
Constant
Object
Description
The Object parameter is the Parameter object to be appended.
Before appending, make sure to set the Type property for the Parameter object. You will also need to set the Size property for variable-length data types. In the example, note the use of the CreateParameter method which is used to create a Parameter object and to set the Name, Type and Direction. (It can also be used to set the Size and Value.)
Parameters.Delete Method
The Delete method deletes a Parameter object from the Parameters Collection. Syntax object.Delete (Index) Arguments Constant
Index
Description
The Index parameter is either the name property or the ordinal position (index) in the collection of the Parameter object.
Parameters.Refresh Method
The Refresh method updates the Parameter objects in the Parameters Collection with the latest information from the provider. Syntax object.Refresh
Before calling Refresh for a Command object, you need to set the ActiveConnection property to an active Connection object, set the CommandText property to a command that will be recognized by the provider, and set the CommandType property to the adCmdStoredProc constant.
85
that, after they have been initially defined and stored, use parameters to change some detail in the text of the command before it is executed. Each time a Parameter object is created, it is added to a Parameters Collection associated with a specific Command object. The Command object uses the Parameters Collection to pass these parameters in and out of the stored procedures and queries. There are four major types of parameters: input, output, input/output and return.
The Attributes property returns a long value defining the characteristics of a Parameter object.
For a Parameter object, the Attributes property is read/write, and its value can be the sum of any one or more ParameterAttributesEnum values. The default is adParamSigned When you set multiple attributes, you can sum the appropriate constants. If you set the property value to a sum including incompatible constants, an error occurs. For a list of ParameterAttributesEnum Values see Table 13 on page 117
Parameter.Direction Property
The Direction property sets or returns a ParameterDirectionEnum value that defines the type of the Parameter object
By direction, we refer to how a Parameter is passed to or from a provider. This can be an input, output, input/output, or a returned value from a stored procedure. You can also set the direction by using the CreateParameter method of the Command object. The default direction for this method is adParamInput. For a list of ParameterDirectionEnum Values see Table 13 on page 117
Parameter.Name Property
The Name property sets or returns a string that is the name of the Parameter object.
86
This property is read/write for Parameter objects that have not been appended to the Parameters Collection. However, the Name property becomes read-only after a Parameter object is appended to the Parameters Collection. Interestingly, names do not have to be unique in the Parameters Collection. You can also set the name using the CreateParameter method of the Command object.
Parameter.NumericScale Property
The NumericScale property sets or returns a byte value that is the number of digits allowed to the right of the decimal point for a numeric Parameter object.
The number of digits stored on the right side is also referred to as the scale of the number.
Parameter.Precision Property
The Precision property sets or returns a byte value that is the maximum number of digits allowed in a numeric Parameter object.
The number of digits stored on the right side is also referred to as the scale of the number and the degree of precision.
Parameter.Size Property
The Size property sets or returns a long value that is the maximum size in bytes or characters of a Parameter object.
If you set a value for a Parameter object to be a variable-length data type, you must specify the Size before appending the object to the Parameters Collection, or an error will be generated. Similarly, if you change the data type of an already appended Parameter object to be a variable-length data type, you must specify the Size before executing the Command object, or an error will be generated. You can use the Refresh method of the Recordset object to have the provider fill in parameter details. Under these circumstances, the provider will set the variable-length data types to be their maximum size and will allocate the necessary memory.
87
Unfortunately, if memory is at a premium, an error may occur when you attempt an execution. Therefore, you may need to check the Size for provider-assigned variable-length data types.
Parameter.Type Property
The Type property sets or returns a DataTypeEnum value that specifies the data type.
Unfortunately, some providers may not support all of the possible data types. If a provider encounters a data type that it does not recognize, it will usually change it to a data type that it does recognize. For a list of DataTypeEnum Values see Table 12 on page 117
Parameter.Value Property
The Value property sets or returns variant value that is the value of the Parameter object.
Before you try to read the Value property, the Recordset should be closed. ADO can read the Value property of a Parameter object only once from the provider.
Parameter.AppendChunk Method
The AppendChunk method used to append a large amount (i.e., a large chunk) of text or binary data to a Parameter object. Syntax object.AppendChunk (Data) Arguments Constant
Data
Description
The Data parameter is a variant that is the binary or text data that you want to add to the Parameter object.
The AppendChunk method is used to append binary or text data to a Parameter object. To use the AppendChunk method, the Attributes property of the specified Parameter object must be set to adParamLong.
88
The first time that you call AppendChunk, the data is not appended, but rather, it overwrites any existing data in the Parameter object. The second time that you call AppendChunk, the data is appended to the existing data. All subsequent calls will also append the data. You can use this method to pass large amounts of data into a Parameter object in reasonable sized chunks.
The Count property returns a long value that is the number of items in the collection. The counting starts at zero. You can use this value to loop through the collection by iterating from zero to the value of Count minus one.
Use the Count property to determine how many objects are in a given collection Because numbering for members of a collection begins with zero, you should always code loops starting with the zero member and ending with the value of the Count property minus 1. If you want to loop through the members of a collection without checking the Count property, use the For Each...Next statement. If the Count property is zero, there are no objects in the collection. You can also use the For Each ... Next statement.
Properties.Item Property
The Item property is used to return a specific member of the Properties Collection. Syntax
89
object.Item (vIndex)
The vIndex parameter is a variant. It is also can be the named item, or the position (ordinal) number.
Properties.Refresh Method
The Refresh method The Refresh method updates the Property objects in the Properties Collection with the dynamic property information specific to the provider. Syntax object.Refresh
It is quite possible that the provider has dynamic properties that are not supported by ADO.
The Attributes property returns a long value that is the sum of one or more FieldAttributeEnum values that define the characteristics of a Property object.
For a Property object, the Attributes property is read-only, and its value can be the sum of any one or more PropertyAttributesEnum values. For a list of PropertyAttributesEnum Values see Table 16 on page 118
90
Property.Name Property
The Name property sets or returns a string value that is the name of the Property object.
The Name property returns a string that is the name of the Property object. The name can also be obtained from the Properties Collection. The Name property is also used by the Command, Field, and Parameter objects.
Property.Type Property
The Type property sets or returns a DataTypeEnum value that specifies the data type.
The Type property returns a DataTypeEnum value which is the data type or operational type of the Property object. Unfortunately, some providers may not support all of the possible data types. If a provider encounters a data type that it does not recognize, it will usually change it to a data type that it does recognize. For a list of DataTypeEnum Values see Table 12 on page 117
Property.Value Property
The Value property sets or returns a variant that is the value of the Property object.
The Value property sets or returns a variant that is the current value of the Property object. Properties can be set to read or write by using the Attributes property. You will not be able to set the Value for properties that are read-only.
91
have a file consisting of last names, first names, and middle initials; the file might look like this:
LastName,FirstName,MiddleInitial Myer,Ken,W Poe, Deborah,L
In this example, the comma is our "delimiter," the character used to separate one field from another. (In fact, comma-separated-value files, or CSVs, are probably the most popular form of delimited file.) Not all text files use the comma as a delimiter; many log files, for example, are tab-delimited files instead. The sample file ago represents a typical CSV file, but it's not the recommended way of doing things. Instead, it's recommended that you surround individual fields with double-quotation marks, like this: "Myer","Ken","W" What's the difference? Well, in this simple case, there really isn't one. But suppose you had a text file like this, where there happens to be a comma in the value:
Address 555 Main Street, Apartment 5
There's only one field, but your script will see two values (555 Main Street and Apartment 5). That's because there's a comma in there, and the script will assume the comma is being used as a delimiter. To keep things clear, format your CSV files like this:
Address "555 Main Street, Apartment 5"
When the comma is embedded in double-quotes, ADO treats it as just another character in a string.
So what's wrong with this? To a certain degree, nothing; it will usually work just fine. Of course, it will work just fine provided you overcome the obstacles presented by the FileSystemObject: No filtering. The nice thing about databases is that you can issue a query like "Select * From Logfile Where Result = 'Error'" and you'll get back only those records
92
where the Result field is equal to error. That can't be done with the FileSystemObject. You might want only the records where Result is equal to Error, but you'll still have to read through the entire file, from top to bottom, checking the value of the Result field each time. That's not necessarily slower (the FileSystemObject is actually pretty darn fast), but it does make your code a bit trickier to write. Difficulty in calculating statistics. Suppose you have a directory of some kind, and you'd like to count the number of people in each of your departments. With a database, you can issue a single query that will return that information in a flash. With the FileSystemObject, well, no such luck. Instead, you'll have to examine each record, and then use an array or a Dictionary object to manually tally up the number of people in each department. This will work, but it's tedious to code (and even more tedious if you have to change that code somewhere down the road). One and done. Another problem with the FileSystemObject is that it's a one-way street, and a dead-end street to boot. What does that mean? Well, suppose you use the FileSystemObject to read through a text file and calculate a statistic of some kind. Now you want to read through it a second time, and calculate a second statistic. Oops, with the FileSystemObject there's no turning back: Once you get to the end of the file, you're done. You can't loop back through your file. Instead, you'll have to close the file and reopen it. Are there ways to work around this? Sure, but that's even more code you'll have to write. Difficulty in getting at the individual fields. When you use the ReadLine method to read in a line from a text file, you get, well, a line from a text file. After all, you want to parse out the user's first name, last name, and middle initial. Unfortunately, all that information, along with an assortment of commas, is glommed together into a single string. By contrast, using database techniques you can essentially say, "Just get me the last name," and ADO will determine which portion of the record represents the user's last name. Much, much easier.
We write a script that reads this line from the file (using the FileSystemObject), and stores the text into a variable named strLine. Our script then runs this code:
arrItems = Split(sLine, ",", -1, 1) For Each sItem in arrItems MsgBox sItem Next
What happens when this block of code runs? We get the following output, with each field (in this case, each letter in the string) now stored as a separate item in the array named arrItems:
93
a b c d e f g
That's exactly the output we want. So why not use Split instead of all that crazy database stuff? Well, two reasons. First, the database code is far more flexible. Suppose we wanted to only extract the values a, d, and f. Can you do that using Split? Sure, but it requires a considerable amount of coding to weed out the unwanted fields. By contrast, a database query can pull out selected values just as easily as it can pull out all the values. Likewise, you can create database queries that will automatically return statistical information from your text file (for example, the number of successful operations versus the number of failed operations). Again, you can read through the text file and calculate these statistics yourself, but it's nowhere near as easy. More important, however, is the fact that the Split function will run into problems if your CSV file includes commas as part of the data, like
105,"cn=Ken Myer,ou=Accounting,ou=North America,dc=fabrikam,dc=com","Fiscal Specialist"
There are only three fields here, and we'd like to get output like this:
105 cn=Ken Myer,ou=Accounting,ou=North America,dc=fabrikam,dc=com Fiscal Specialist
Not only did Split get "fooled" by the commas in the distinguished name, but it left the double-quote marks in as well. ADO can seamlessly handle double-quotes around individual fields and individual values; Split cannot.
94
particular, you need to indicate that this is a text file, you need to specify whether or not the file has a header row, and you need to tell ADO whether this is a delimited or fixed-width file. In your Microsoft SQL query, specify the name of the text file you want to work with. Don't specify the entire path name; remember, we've already indicated the folder where the file is stored. If you're used to working with SQL queries, you put the file name in the spot where you would typically put the table name.
sPathFile = "C:\Databases\" oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & sPathFile & ";" & _ "Extended Properties=""text;HDR=YES;FMT=Delimited""" oRst.Open "SELECT * FROM PhoneList.csv", _ oConn, adOpenStatic, adLockOptimistic, adCmdText
Description
Fields in the file are separated by tabs Fields in the file are separated by commas (note that there should not be a space between the comma and the start of the next field name or value) Fields in the file are separated by some character other than a tab or a comma (with one exception: you can't use the double-quote as a delimiter Fields in a file take up a specific number of characters. If a value is too long, "extra" characters are chopped off the end. If a value is too short, blank spaces are appended to it to make it fill out the requisite number of characters.
Schema Syntax
Format = TabDelimited Format = CSVDelimited Format = Delimited (x) where x represents the character used as the delimiter.
Custom Delimited
Fixed-Length
95
oConn.Mode = adModeRead '--- connection using an ODBC DSN oConn.Open "QT_Flight32" If oConn.State = adStateOpen Then With DataTable.LocalSheet '--- ADODB.Connection.Attributes .GetParameter("Property").ValuebyRow(1) ="Attributes" .GetParameter("Value").ValuebyRow(1) = oConn.Attributes '--- ADODB.Connection.CommandTimeout .GetParameter("Property").ValuebyRow(2) ="CommandTimeout" .GetParameter("Value").ValuebyRow(2) = oConn.CommandTimeout & " sec." '--- ADODB.Connection.ConnectionString .GetParameter("Property").ValuebyRow(3) ="ConnectionString" .GetParameter("Value").ValuebyRow(3) = oConn.ConnectionString '--- ADODB.Connection.ConnectionTimeout .GetParameter("Property").ValuebyRow(4) ="ConnectionTimeout" .GetParameter("Value").ValuebyRow(4) = oConn.ConnectionTimeout & " sec." '--- ADODB.Connection.CursorLocation .GetParameter("Property").ValuebyRow(5) ="CursorLocation" .GetParameter("Value").ValuebyRow(5) = oConn.CursorLocation '--- ADODB.Connection.DefaultDatabase .GetParameter("Property").ValuebyRow(6) ="DefaultDatabase" .GetParameter("Value").ValuebyRow(6) = oConn.DefaultDatabase '--- ADODB.Connection.IsolationLevel .GetParameter("Property").ValuebyRow(7) ="IsolationLevel" .GetParameter("Value").ValuebyRow(7) = oConn.IsolationLevel '--- ADODB.Connection.Mode .GetParameter("Property").ValuebyRow(8) ="Mode" .GetParameter("Value").ValuebyRow(8) = oConn.Mode '--- ADODB.Connection.Provider .GetParameter("Property").ValuebyRow(9) ="Provider" .GetParameter("Value").ValuebyRow(9) = oConn.Provider '--- ADODB.Connection.State .GetParameter("Property").ValuebyRow(10) = "State" .GetParameter("Value").ValuebyRow(10) = oConn.State
'--- ADODB.Connection.Version
.GetParameter("Property").ValuebyRow(11) ="Version" .GetParameter("Value").ValuebyRow(11) = oConn.Version End with
96
Figure 8 Connection Properties, Results Figure shows the watch Expressions pane after executing oConn.Open method
97
If oConn.State = adStateOpen Then Reporter.ReportEvent micDone, "Properties Count", oConn.Properties.Count oConn.Properties.Refresh For Each oProperty In oConn.Properties DataTable.LocalSheet.SetCurrentRow nRow : nRow = nRow + 1 DataTable("Property_Name", dtLocalsheet) = oProperty.Name DataTable("Property_Type", dtLocalsheet) = oProperty.Type DataTable("Property_Value", dtLocalsheet)= oProperty.Value DataTable("Property_Attr", dtLocalsheet)= oProperty.Attributes Next '--- Closing connection oConn.Close Else Reporter.ReportEvent micFail, "oConn.Open", "Failed." End If '--- Exporting to external excel file DataTable.ExportSheet "C:\ConnectionDemo.xls", DataTable.LocalSheet.Name Set oConn = Nothing
98
Set oConn = CreateObject("ADODB.Connection") '--- Open a Connection using an ODBC DSN named "QT_Flight32". oConn.Open "QT_Flight32", "MyUserName", "MyPassword" '--- Find out if the attempt to connect worked. If oConn.State = adStateOpen Then MsgBox "Welcome to Flight Reservation!" Else MsgBox "Sorry. No Flight Reservation today." End If '--- Close the connection if opened. If oConn.State = adStateOpen Then oConn.Close Set oConn = Nothing
If you need to connect to only one data store, the procedure followed in the above code is the easiest way. Alternatively, you can create a Connection object and set the ConnectionString property before calling the Open method. This approach allows you to connect to one data store and then reuse the Connection object to connect to another data store. Also This method also gives you the opportunity to set other properties of the Connection object before connecting.
Option Explicit Const adStateOpen = &H00000001 Dim oConn Set oConn = CreateObject("ADODB.Connection") '--- Open a Connection using an ODBC DSN named "QT_Flight32". oConn.ConnectionString "DSN=QT_Flight32;UID=MyUserName;PWD=MyPassword;" oConn.ConnectionTimeout = 30 oConn.Open '--- Find out if the attempt to connect worked. If oConn.State = adStateOpen Then MsgBox "Welcome to Flight Reservation!" Else MsgBox "Sorry. No Flight Reservation today." End If '--- Close the connection if opened. If oConn.State = adStateOpen Then oConn.Close Set oConn = Nothing
99
oConn.Open "QT_Flight32" '--- Find out if the attempt to connect worked. If oConn.State = adStateOpen Then Set oRst = oConn.Execute("SELECT * FROM ORDERS") If oRst.State = adStateOpen Then '--- Show the first order. MsgBox oRst("Order_Number") & " : " & oRst("Customer_Name") End If End If '--- Close the recordset if opened. If oRst.State = adStateOpen Then oRst.Close '--- Close the connection if opened. If oConn.State = adStateOpen Then oConn.Close Set oRst = Nothing : Set oConn = Nothing
How to connect to QuickTest demo Flight Reservation application using a connection string?
The Connection string to the flight Reservation demo application:
Option Explicit On Error Resume Next Private Const adStateOpen = 1 Dim oFSO, oConn Dim sConnStr, sProvider, sDataSrc sProvider = "Microsoft.Jet.OLEDB.4.0" Set oFSO = CreateObject("Scripting.FileSystemObject") '--- Dynamically building the data source string path sDataSrc = oFSO.BuildPath(Environment("ProductDir"),"samples\flight\app\flight32.mdb") sConnstr = "Provider=" & sProvider & ";Data Source=" & sDataSrc '--- Save the connection string for later use Environment.Value("FlightConnStr") = sConnstr '--- connecting to database Set oConn = CreateObject("ADODB.Connection") oConn.ConnectionString = Environment.Value("FlightConnStr") oConn.Open If oConn.State = adStateOpen Then Msgbox "Connected Successfully!", vbInformation, "Connect" oConn.Close Else Msgbox "Connection Failed", vbCritical , "Connect" End If Set oConn = Nothing : Set oFSO = Nothing
100
101
Dim sSQL '--- connecting to database Set oConn = CreateObject("ADODB.Connection") oConn.Open "QT_Flight32" '--- Querying Database Set oRst = CreateObject("ADODB.Recordset") sSQL = "Orders" oRst.Open sSQL, oConn, adOpenStatic, adLockOptimistic, adCmdTable '-- Retriving the last Order_Number and add 1 to value oRst.MoveFirst '--- Saving the recordset oRst.Save "C:\out_order.xml", adPersistXML '--- Closing and reset variables If oRst.State = adStateOpen Then oRst.Close If oConn.State = adStateOpen Then oConn.Close Set oRst = Nothing : Set oConn = Nothing The following result, is displayed with Altova XML spy application. http://www.altova.com/products/xmlspy/xml_editor.html
102
Option Explicit Private Const adStateOpen = 1 Private Const adOpenStatic = 3 Private Const adLockOptimistic = 3 Private Const adCmdTaext = 1 Dim oConn, oRst Dim sSQL '--- connecting to database Set oConn = CreateObject("ADODB.Connection") oConn.Open "QT_Flight32" '--- Querying Database Set oRst = CreateObject("ADODB.Recordset") sSQL = "SELECT TOP 3 * FROM Orders " & _ "ORDER BY Tickets_Ordered DESC" oRst.Open sSQL, oConn, adOpenStatic, adLockOptimistic, adCmdText '--- Counting records (should be 3) If oRst.RecordCount = 3 Then Reporter.ReportEvent micPass, "Query", "Query Success" Else Reporter.ReportEvent micFail, "Query", "Query is not successfull" End If '--- Closing and reset variables If oRst.State = adStateOpen Then oRst.Close If oConn.State = adStateOpen Then oConn.Close Set oRst = Nothing : Set oConn = Nothing
103
Msgbox "Record found, Customer_Name: " & oRst.Fields("Customer_Name") End If '--- Closing and reset variables If oRst.State = adStateOpen Then oRst.Close If oConn.State = adStateOpen Then oConn.Close Set oRst = Nothing : Set oConn = Nothing
104
Set oRst = CreateObject("ADODB.Recordset") sSQL = "Flights" oRst.Open sSQL, oConn, adOpenStatic, adLockOptimistic, adCmdTable '--- Setting search criteria sSearch = "Departure='Seattle' AND Arrival='London' AND Day_Of_Week='Sunday'" oRst.Filter = sSearch MsgBox "Found: " & oRst.RecordCount & " records.", _ vbInformation, "Seattle --> London" '--- Closing and reset variables If oRst.State = adStateOpen Then oRst.Close If oConn.State = adStateOpen Then oConn.Close Set oRst = Nothing : Set oConn = Nothing
Is it important that your text files be formatted like this? Its not just important, its crucial. Were going to use database techniques to retrieve information from the file, and to do that the file needs to be delimited in some way (in this case, using the comma as the delimiter). Ideally, your files should include a header row as well. As long as your text file looks like this youre in business.
Option Explicit Const adOpenStatic = 3 Const adLockOptimistic = 3 Const adCmdText = &H0001 Dim oConn, oRst Dim sFile, sPath, sSQL, sOut Set oConn = CreateObject("ADODB.Connection") Set oRst = CreateObject("ADODB.Recordset") sPath = "C:\Samples" : sFile = "Employees.txt" oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _ "Data Source=" & sPath & ";" & "Extended Properties=""text;HDR=YES;FMT=Delimited""" sSQL = "Select * FROM " & sFile & " where Department = 'QA'" oRst.Open sSQL,oConn, adOpenStatic, adLockOptimistic, adCmdText Do Until oRst.EOF sOut = oRst.Fields.Item("LastName").Value & vbCrLf sOut = sOut & oRst.Fields.Item("FirstName").Value & vbCrLf sOut = sOut & oRst.Fields.Item("Role").Value & vbCrLf MsgBox sOut oRst.MoveNext Loop oRst.Close : oConn.Close
105
106
How Can I Get a List of the ODBC Drivers that are Installed on a Computer? How Can I Retrieve a List of the System DSNs on a Computer? Appendix 14.A ADODB Constants ADODB Constants
XacAttributeEnum Values
Constant
adXactCommitRetaining adXactAbortRetaining
Value
262144 131072
Description
Ensures that calling the RollbackTrans method automatically starts a new transaction Ensures that calling the CommitlbackTrans method automatically starts a new transaction
CursorLocationEnum Values
Constant
adUseNone adUseServer adUseClient
Value
0 2 3
Description
This constant is obsolete and appears solely for the sake of backward compatibility. Uses a server-side cursor provided by the local library Uses a client-side cursor provided by the local library
IsolationLevelEnum Values
Constant
adXactUnspecified adXactChaos adXactReadUncommitted adXactBrowse adXactReadCommitted adXactCursorStability
Value
-1 16 256 256 4096 4096
Description
Cannot use the provided isolation level and cannot determine the isolation level Default. Indicates that you cannot overwrite pending changes from more highly isolated transactions. Same as adXactBrowse. Indicates that from one transaction you can view uncommitted changes in other transactions. Same as adXactCursorStability. Default. Indicates that from one transaction you can view changes in other transactions only after they've been committed Indicates that from one transaction you cannot see changes made in other transactions, but that requerying can bring new recordsets.
adXactRepeatableRead
65536
107
adXactSerializable adXactIsolated
1048576 1048576
Same as adXactIsolated. Indicates that transactions are conducted in isolation of other transactions.
ConnectModeEnum Values
Constant
adModeUnknown adModeRead adModeWrite adModeReadWrite adModeShareDenyRead adModeShareDenyWrite adModeShareExclusive adModeShareDenyNone
Value
0 1 2 3 4 8 12 16
Description
Permissions cannot be set or determined Indicates read-only permissions. Indicates write-only permissions. Indicates read/write permissions. Prevents others from opening connection with read permissions. Prevents others from opening connection with write permissions. Prevents others from opening connection. Prevents others from opening connection with any permissions.
ObjectStateEnum Values
Constant
adStateClosed adStateOpen adStateConnecting adStateExecuting adStateFetching
Value
0 1 2 4 8
Description
Default. Indicates that the object is closed. Indicates that the object is open. Indicates that the Recordset object is connecting. Indicates that the Recordset object is executing a command. Indicates that the rows of the Recordset object are being fetched.
ExecuteOptionEnum Values
Parameter
adAsyncExecute adAsyncFetch adAsyncFetchNonBlocking adExecuteNoRecords adOptionUnspecified
Value
16 32 64 128 -1
Description
Execute asynchronously Rows beyond the initial quantity specified should be fetched asynchronously Records are fetched asynchronously with no blocking of additional operations Does not return rows and must be combined with adCmdText or adCmdStoredProc The option parameter is unspecified
108
CommandTypeEnum Values
Parameter
adCmdText adCmdTable adCmdTableDirect adCmdFile adCmdStoredProc adCmdUnknown adCmdUnspecified
Value
1 2 512 256 4 8 -1
Description
Evaluate as a textual definition Have the provider generate a SQL query and return all rows from the specified table Return all rows from the specified table Evaluate as a previously persisted file Evaluate as a stored procedure The type of the CommandText parameter is unknown Default, does not specify how to evaluate
ConnectOptionEnum Values
Constant
adAsyncConnect adConnectUnspecified
Value
16 -1
Description
Open an asynchronous connection which returns before the connection is completed Default, open a synchronous connection which returns after the connection is completed
Value
0
Description
Returns the assertions Returns the catalog information Returns the defined character set in the catalog Returns the defined check constraints in the catalog Returns the defined character collations in the catalog Returns the columns that are domain dependent
Constraint Columns
CONSTRAINT_CATALOG CONSTRAINT_SCHEMA CONSTRAINT_NAME CATALOG_NAME CHARACTER_SET_CATALOG CHARACTER_SET_SCHEMA CHARACTER_SET_NAME CONSTRAINT_CATALOG CONSTRAINT_SCHEMA CONSTRAINT_NAME COLLATION_CATALOG COLLATION_SCHEMA COLLATION_NAME DOMAIN_CATALOG DOMAIN_SCHEMA DOMAIN_NAME COLUMN_NAME TABLE_CATALOG TABLE_SCHEMA TABLE_NAME COLUMN_NANE GRANTOR GRANTEE
adSchemaCatalogs
adSchemaCharacterSets
adSchemaCheckConstraints
adSchemaCollations
adSchemaColumnDomainUsage
11
adSchemaColumnPrivileges
13
109
adSchemaColumns
TABLE_CATALOG TABLE_SCHEMA TABLE_NAME COLUMN_NANE COLUMN_NANE TABLE_CATALOG TABLE_SCHEMA TABLE_NAME TABLE_CATALOG TABLE_SCHEMA TABLE_NAME CATALOG_NAME SCHEMA_NAME CUBE_NAME none
adSchemaConstraintColumnUsage
adSchemaConstraintTableUsage
Returns the tables used by constraints Returns info about the cubes used for multidimensional data Return the keywords recognized by the provider Return the literals used in text commands by the provider
adSchemaCubes
32
adSchemaDBInfoKeywords
30
adSchemaDBInfoLiterals
31
none CATALOG_NAME SCHEMA_NAME CUBE_NAME DIMENSION_NAME DIMENSION_UNIQUE_NAME PK_TABLE_CATALOG PK_TABLE_SCHEMA PK_TABLE_NAME FK_TABLE_CATALOG FK_TABLE_SCHEMA FK_TABLE_NAME TABLE_CATALOG TABLE_SCHEMA INDEX_NAME TYPE TABLE_NAME COLUMN_NAME CONSTRAINT_CATALOG CONSTRAINT_SCHEMA CONSTRAINT_NAME TABLE_CATALOG TABLE_SCHEMA TABLE_NAME CATALOG_NAME SCHEMA_NAME CUBE_NAME DIMENSION_UNIQUE_NAME HIERARCHY_UNIQUE_NAME LEVEL_NAME LEVEL_UNIQUE_NAME CATALOG_NAME SCHEMA_NAME CUBE_NAME MEASURE_NAME MEASURE_UNIQUE_NAME CATALOG_NAME SCHEMA_NAME CUBE_NAME
adSchemaDimensions
33
adSchemaForeignKeys
27
adSchemaIndexes
12
adSchemaKeyColumnUsage
adSchemaLevels
35
adSchemaMeasures
36
Returns the measures for multi-dimensional data Returns the available members for multidimensional data
adSchemaMembers
38
110
DIMENSION_UNIQUE_NAME HIERARCHY_UNIQUE_NAME LEVEL_UNIQUE_NAME LEVEL_NUMBER MEMBER_NAME MEMBER_UNIQUE_NAME MEMBER_CAPTION MEMBER_TYPE TREE OPERATOR adSchemaPrimaryKeys 28 Returns the primary key columns Returns info on columns returned by stored procedures Returns info on the parameters and return codes of stored procedures Returns info on the stored procedures PK_TABLE_CATALOG PK_TABLE_SCHEMA PK_TABLE_NAME PROCEDURE_CATALOG PROCEDURE_SCHEMA PROCEDURE_NAME COLUMN_NAME PROCEDURE_CATALOG PROCEDURE_SCHEMA PROCEDURE_NAME PARAMETER_NAME PROCEDURE_CATALOG PROCEDURE_SCHEMA PROCEDURE_NAME PROCEDURE_TYPE CATALOG_NAME SCHEMA_NAME CUBE_NAME DIMENSION_UNIQUE_NAME HIERARCHY_UNIQUE_NAME LEVEL_UNIQUE_NAME MEMBER_UNIQUE_NAME PROPERTY_TYPE PROPERTY_NAME CATALOG_NAME SCHEMA_NAME SCHEMA_OWNER none TABLE_CATALOG TABLE_SCHEMA TABLE_NAME CONSTRAINT_CATALOG CONSTRAINT_SCHEMA CONSTRAINT_NAME TABLE_CATALOG TABLE_SCHEMA TABLE_NAME CONSTRAINT_TYPE TABLE_CATALOG TABLE_SCHEMA TABLE_NAME GRANTOR GRANTEE TABLE_CATALOG TABLE_SCHEMA TABLE_NAME TABLE_TYPE TRANSLATION_CATALOG
adSchemaProcedureColumns
29
adSchemaProcedureParameters
26
adSchemaProcedures
16
adSchemaProperties
37
adSchemaSchemata
17
Returns the schema owned by a user Returns the SQL language support info Returns the defined statistics in a catalog
adSchemaSQLLanguages
18
adSchemaStatistics
19
adSchemaTableConstraints
10
adSchemaTablePrivileges
14
adSchemaTables
20
adSchemaTranslations
21
111
TRANSLATION_SCHEMA TRANSLATION_NAME none OBJECT_CATALOG OBJECT_SCHEMA OBJECT_NAME OBJECT_TYPE GRANTOR GRANTEE VIEW_CATALOG VIEW_SCHEMA VIEW_NAME TABLE_CATALOG TABLE_SCHEMA TABLE_NAME VIEW_CATALOG VIEW_SCHEMA VIEW_NAME
adSchemaUsagePrivileges
15
adSchemaViewColumnUsage
24
Returns the column usage for viewed tables Returns the views info from the catalog Returns the table usage for viewed tables
adSchemaViews
23
adSchemaViewTableUsage
25
PersistFormatEnum Values
Constant adPersistADTG adPersistXML Value 0 1 Description Save in the Microsoft Advanced Data TableGram (ADTG) format Save in XML format.
ErrorValueEnum Values
Constant
adErrBoundToCommand
Value
3707 -2146824581 0x800A0E7B 3732 -2146824556 0x800A0E94 3748 -2146824540 0x800A0EA4 3220 -2146825068 0x800A0C94 3724 -2146824564 0x800A0E8C 3725 -2146824563 0x800A0E8D 3747 -2146824541
Description
Cannot change the ActiveConnection property
adErrCannotComplete
adErrCantChangeConnection
adErrCantChangeProvider
adErrCantConvertvalue
adErrCantCreate
Data value cannot be set or returned due to wrong data type or insufficient resources Need a valid ParentCatalog
adErrCatalogNotSet
112
0x800A0EA3 3726 -2146824562 0x800A0E8E 3421 -2146824867 0x800A0D5D 3721 -2146824567 0x800A0E89 3738 -2146824550 0x800A0E9A 3750 -2146824538 0x800A0EA6 3751 -2146824537 0x800A0EA7 3251 -2146825037 0x800A0CB3 3749 -2146824539 0x800A0EA5 3219 -2146825069 0x800A0C93 3719 -2146824569 0x800A0E87 3246 -2146825042 0x800A0CAE 3001 -2146825287 0x800A0BB9 3709 -2146824579 0x800A0E7D 3708 -2146824580 0x800A0E7C 3714 -2146824574 0x800A0E82 3729 -2146824559 0x800A0E91 3265 -2146825023 0x800A0CC1 3021 -2146825267
adErrColumnNotOnThisRow
adErrDataConversion
adErrDataOverflow
adErrDelResOutOfScope
adErrDenyNotSupported
Sharing restrictions not supported by provider Requested sharing restriction not recognized by provider
adErrDenyTypeNotSupported
adErrFeatureNotAvailable
adErrFieldsUpdateFailed
adErrIllegalOperation
adErrIntegrityViolation
adErrInTransaction
adErrInvalidArgument
adErrInvalidConnection
adErrInvalidParamInfo
adErrInvalidTransaction
adErrInvalidURL
adErrItemNotFound
adErrNoCurrentRecord
113
0x800A0BCD 3715 -2146824573 <0x800A0E83 3710 -2146824578 0x800A0E7E 3704 -2146824584 0x800A0E78 3367 -2146824921 0x800A0D27 3420 -2146824868 0x800A0D5C 3705 -2146824583 0x800A0E79 3002 -2146825286 0x800A0BBA 3712 -2146824576 0x800A0E80 3734 -2146824554 0x800A0E96 3720 -2146824568 0x800A0E88 3742 -2146824546 0x800A0E9E 3739 -2146824549 0x800A0E9B 3740 -2146824548 0x800A0E9C 3741 -2146824547 0x800A0E9D 3743 -2146824545 0x800A0E9F 3744 -2146824544 0x800A0EA0 3745 -2146824543 0x800A0EA1 3746 -2146824542
adErrNotExecuting
adErrNotReentrant
adErrObjectClosed
adErrObjectInCollection
adErrObjectNotSet
Invalid Object
adErrObjectOpen
adErrOpeningFile
adErrOperationCancelled
adErrOutOfSpace
Out of memory
adErrPermissionDenied
adErrPropConflicting
adErrPropInvalidColumn
adErrPropInvalidOption
adErrPropInvalidValue
adErrPropNotAllSettable
adErrPropNotSet
adErrPropNotSettable
adErrPropNotSupported
114
0x800A0EA2 3000 -2146825288 0x800A0BB8 3706 -2146824582 0x800A0E7A 3003 -2146825285 0x800A0BBB 3731 -2146824557 0x800A0E93 3730 -2146824558 0x800A0E92 3735 -2146824553 0x800A0E97 3722 -2146824566 0x800A0E8A 3723 -2146824565 0x800A0E8B 3713 -2146824575 0x800A0E81 3711 -2146824577 0x800A0E7F 3728 -2146824560 0x800A0E90 3736 -2146824552 0x800A0E98 3716 -2146824572 0x800A0E84 3727 -2146824561 0x800A0E8F 3737 -2146824551 0x800A0E99 3004 -2146824555 0x800A0E95 3004 -2146825284 0x800A0BBC 3717 -2146824571
adErrProviderFailed
adErrProviderNotFound
adErrReadFile
adErrResourceExists
adErrResourceLocked
adErrResourcesOutOfScope
adErrSchemaViolation
Data type or constraints conflict with data value Data value is signed and field data is unsigned Operation cannot be performed until connection completed
adErrSignMismatch
adErrStillConnecting
adErrStillExecuting
adErrTreePermissionDenied
adErrUnavailable
adErrUnsafeOperation
adErrURLDoesNotExist
adErrURLNamedRowDoesNotExist
adErrVolumeNotFound
adErrWriteFile
adWrnSecurityDialog
Not used
115
adWrnSecurityDialogHeader
Not used
DataTypeEnum Constants
Constant
adArray adBigInt adBinary adBoolean adBSTR adChapter adChar adCurrency adDate adDBDate adDBFileTime adDBTime adDBTimeStamp adDecimal adDouble adEmpty adError adFileTime adGUID adIDispatch adInteger adIUnknown adLongVarBinary adLongVarChar adLongVarWChar adNumeric adPropVariant adSingle adSmallInt adTinyInt adUnsignedBigInt
Value
0x2000 20 128 11 8 136 129 6 7 133 137 134 135 14 5 0 10 64 72 9 3 13 205 201 203 131 138 4 2 16 21
Description
Combine with another data type to indicate that the other data type is an array 8-byte signed integer Binary True or false Boolean Null-terminated character string 4-byte chapter value for a child recordset String Currency format Number of day since 12/30/1899 YYYYMMDD date format Database file time HHMMSS time format YYYYMMDDHHMMSS date/time format Number with fixed precision and scale Double precision floating-point no value 32-bit error code Number of 100-nanosecond intervals since 1/1/1601 Globally unique identifier Currently not supported by ADO 4-byte signed integer Currently not supported by ADO Long binary value Long string value Long Null-terminates string value Number with fixed precision and scale PROPVARIANT automation Single-precision floating-point value 2-byte signed integer 1-byte signed integer 8-byte unsigned integer
116
adUnsignedInt adUnsignedSmallInt adUnsignedTinyInt adUserDefined adVarBinary adVarChar adVariant adVarNumeric adVarWChar adWChar
4-byte unsigned integer 2-byte unsigned integer 1-byte unsigned integer User-defined variable Binary value String Automation variant Variable width exact numeric with signed scale Null-terminated Unicode character string Null-terminated Unicode character string
ParameterDirectionEnum Constants
Constant
adParamInput adParamInputOutput adParamOutput adParamReturnValue adParamUnknown
Value
1 3 2 4 0
Description
Input parameter Both input and output parameter Output parameter Return value Direction is unknown
ParameterAttributesEnum Constants
Constant
adParamLong adParamNullable adParamSigned
Value
128 64 16
Description
Indicates that the parameter accepts long binary data. Indicates that the parameter accepts Null values. Default. Indicates that the parameter accepts signed values.
FieldAttributesEnum Constants
Constant
adFldCacheDeferred adFldFixed adFldIsChapter adFldIsCollection adFldIsDefaultStream
Value
4096 16 &H10 8192 &H2000 262144 &H40000 131072 &H20000
Description
117
32 &H20 65536 &H10000 32768 &H8000 128 &H80 64 &H40 2 16384 &H4000 256 &H100 512 &H200 8 4
adFldLong
Indicates that the field is a long binary field. Also indicates that you can use the AppendChunk and GetChunk methods. Indicates that you can read Null values from the field. Indicates that the field is deferred; that is, the field values are not retrieved from the data source with the whole record, but only when you explicitly access them.
adFldMayBeNull
adFldMayDefer
adFldNegativeScale
adFldRowID
Indicates that the field contains a persistent row identifier that cannot be written to and has no meaningful value except to identify the row (such as a record number, unique identifier, and so forth). Indicates that the field contains some kind of time or date stamp used to track updates. Indicates that the provider cannot determine if you can write to the field. Indicates that you can write to the field.
PropertyAttributesEnum Constants
Constant
adPropNotSupported adPropOptional adPropRead adPropRequired adPropWrite
Value
0 2 512 &H200 1 1024 &H400
Description
Indicates that the provider does not support the property. Indicates that the user does not need to specify a value for this property before the data source is initialized. Indicates that the user can read the property. Indicates that the user must specify a value for this property before the data source is initialized. Indicates that the user can set the property.
ParameterAttributesEnum Constants
Constant
adDefaultStream adRecordURL
Value
-1 -2
Description
References the field containing the default stream References the field containing the absolute URL
118
FieldStatusEnum Constants
Constant
adFieldAlreadyExists adFieldBadStatus
Value
26 &H1A 12
Description
Indicates that the specified field already exists. Indicates that an invalid status value was sent from ADO to the OLE DB provider. Possible causes include an OLE DB 1.0 or 1.1 provider, or an improper combination of Value and Status. Indicates that the server of the URL specified by Source could not complete the operation Indicates that during a move operation, a tree or sub-tree was moved to a new location, but the source could not be deleted. Indicates that the field cannot be retrieved or stored without loss of data. Indicates that the field could not be added because the provider exceeded a limitation (such as the number of fields allowed). Indicates that the data returned from the provider overflowed the data type of the field. Indicates that the default value for the field was used when setting data. Indicates that the field specified does not exist. Indicates that this field was skipped when setting data values in the source. The provider set no value. Indicates that the field cannot be modified because it is a calculated or derived entity. Indicates that the data source URL contains invalid characters. Indicates that the provider returned a VARIANT value of type VT_NULL and that the field is not empty. Default. Indicates that the field was successfully added or deleted. Indicates that the provider is unable to obtain enough storage space to complete a move or copy operation. Indicates either that the field has been deleted and then re-added, perhaps with a different data type, or that the value of the field that previously had a status of adFieldOK has changed. The final form of the field will modify the Fields collection after the Update method is called. Indicates that the Delete operation caused the status to be set. The field has been marked for deletion from the Fields collection after the Update method is called. Indicates that the Append operation caused the status to be set. The Field has been marked to be added to the Fields collection after the Update method is called. Indicates that the provider cannot determine what
20 &H14 23 &H17 2 7
adFieldDataOverflow adFieldDefault adFieldDoesNotExist adFieldIgnore adFieldIntegrityViolation adFieldInvalidURL adFieldIsNull adFieldOK adFieldOutOfSpace adFieldPendingChange
adFieldPendingDelete
adFieldPendingInsert
adFieldPendingUnknown
119
operation caused field status to be set. Indicates that the provider cannot determine what operation caused field status to be set, and that the field will be deleted from the Fields collection after the Update method is called. Indicates that the field cannot be modified because it is defined as read-only. Indicates that the field in the data source is defined as read-only. Indicates that the provider was unable to perform the operation because an object already exists at the destination URL and it is not able to overwrite the object. Indicates that the provider was unable to perform the operation because the data source is locked by one or more other application or process. Indicates that a source or destination URL is outside the scope of the current record. Indicates that the value violated the data source schema constraint for the field. Indicates that data value returned by the provider was signed but the data type of the ADO field value was unsigned. Indicates that variable-length data was truncated when reading from the data source. Indicates that the provider could not determine the value when reading from the data source. For example, the row was just created, the default value for the column was not available, and a new value had not yet been specified. Indicates that the provider is unable to locate the storage volume indicated by the URL.
adFieldResourceLocked
adFieldTruncated adFieldUnavailable
4 8
adFieldVolumeNotFound
21 &H15
ResyncEnum Constants
Constant
adResyncAllValues adResyncUnderlyingValues
Value
2 1
Description
Default, can overwrite all values, and pending updates are cancelled Can only overwrite underlying values, and pending updates are not cancelled
RecordTypeEnum Constants
Constant
adCollectionRecord adSimpleRecord adStructDoc
Value
1 0 2
Description
Type is a collection record that does contain children Type is a simple record that does not contain children Type is a COM structured document
120
CopyRecordOptionsEnum Constants
Constant Value Description
If the attempt to copy the records failed, because the Destination is on a different server or uses a different provider than the Source, then the Source provider can attempt to simulate the copy by using upload, download, and delete operations. Copies the directory, but not any subdirectories Type is a COM structured document Default. Performs the default copy operation: The operation fails if the destination file or directory already exists, and the operation copies recursively.
adCopyAllowEmulation
2 1 -1
MoveRecordOptionsEnum Constants
Constant Value Description
If the attempt to move the records failed, because the Destination is on a different server or uses a different provider than the Source, then the Source provider can attempt to simulate the move by using upload, download, and delete operations. Does not update links of source Record Allows files and directories at destination to be overwritten Default, does not allow overwrite but does update links
adMoveAllowEmulation
2 1 -1
RecordCreateOptionsEnum Constants
Constant
adCreateCollection adCreateNonCollection adCreateOverwrite
Value
8192 &H2000 0 67108864 &H4000000 -2147483648 &H80000000 -1 33554432 &H2000000
Description
Create a new Record specified by Source parameter Create a new Record of type adSimpleRecord Allows overwrite of existing Record You must OR this constant with adCreateCollection, adCreateNonCollection, or adCreateStructDoc Create a new Record of type adStructDoc Default Provider must open existing Record You must OR this constant with adCreateCollection, adCreateNonCollection, or adCreateStructDoc
121
RecordOpenOptionsEnum Constants
Constant
adDelayFetchFields adDelayFetchStream adOpenAsync adOpenExecuteCommand adOpenOutput adOpenRecordUnspecified
Value
32768 &H8000 16384 &H4000 4096 &H1000 65536 &H10000 8388608 &H800000 -1
Description
Retrieve fields associated with Record only when needed Retrieve stream associated with Record only when needed Open in an asynchronous mode
PositionEnum Constants
Constant
adPosUnknown adPosBOF adPosEOF
Value
-1 -2 -3
Description
The Recordset is empty, the current position is unknown, or not supported by the provider The current record pointer is before the first record at the beginning of the file. The current record pointer is after the last record at the end of the file.
CursorTypeEnum Constants
Constant
adOpenDynamic
Value
2
Description
A dynamic cursor with both forward and backward scrolling where additions, deletions, insertions, and updates made by other users are visible Default, a forward scrolling only, static cursor where changes made by other users are not visible A keyset cursor allows you to see dynamic changes to a specific group of records but you cannot see new records added by other users A static cursor allowing forward and backward scrolling of a fixed, unchangeable set of records Cursor type not specified
adOpenForwardOnly
adOpenKeyset
adOpenStatic adOpenUnspecified
3 -1
EditModeEnum Constants
Constant Value Description
122
2 4 1 0
The current record is new and has been added using the AddNew method but is not saved in the database The current record has been deleted. The current record has been changed but not saved in the database The current record is not being edited
FilterGroupEnum Constants
Constant
adFilterAffectedRecords adFilterConflictingRecords adFilterFetchedRecords adFilterNone adFilterPendingRecords
Value
2 5 3 0 1
Description
This filter only displays records changed by the last call to CancelBatch, Delete, Resync, or Update This filter displays only those records that failed the last batch update This filter displays the records in the current cache Removes the current filter and all underlying records become visible. This filter displays changed records that have not been saved
LockTypeEnum Constants
Constant
adLockBatchOptimistic adLockOptimistic adLockPessimistic adLockReadOnly adLockUnspecified
Value
4 3 2 1 -1
Description
Multiple users can modify the data and the changes are cached until BatchUpdate is called Multiple users can modify the data which is not locked until Update is called The provider locks each record before and after you edit, and prevents other users from modifying the data Read-only data Lock type unknown
MarshalOptionEnum Constants
Constant
adMarshallAll adMarshallModifiedOnly
Value
0 1
Description
Returns all records to the server Return only modified records to the server
RecordStatusEnum Constants
Constant Value Description
123
adRecCanceled adRecCantRelease adRecConcurrencyViolation adRecDBDeleted adRecDeleted adRecIntegrityViolation adRecInvalid adRecMaxChangesExceeded adRecModified adRecMultipleChanges adRecNew adRecObjectOpen adRecOK adRecOutOfMemory adRecPendingChanges adRecPermissionDenied adRecSchemaViolation adRecUnmodified
0x100 0x400 0x800 0x40000 0x4 0x1000 0x10 0x2000 0x2 0x40 0x1 0x4000 0 0x8000 0x80 0x10000 0x20000 0x8
Operation canceled and record not saved Cannot save new record because existing record is locked Optimistic concurrency in effect, record not saved Record has already been deleted Record was successfully deleted Integrity constraints violation, record not saved Bookmark is invalid, record not saved Too many pending changes, record not saved Record was modified Record not saved because it would have affected other records New record Conflict with open storage object, record not saved Record was successfuly updated Computer out of memory, record not saved Due to pending insert, record not changed User does not have permissions Violation of underlying database, record not saved Record has not been changed
AffectEnum Constants
Constant
adAffectAll adAffectAllChapters adAffectCurrent adAffectGroup
Value
3 4 1 2
Description
Cancels all pending updates including those hidden by a filter Cancels all pending updates in all child (chapter) recordsets Cancels only the current record Cancels updates only on records that passed through the filter in effect
CompareEnum Constants
Constant
adCompareEqual adCompareGreaterThan adCompareLessThan adCompareNotComparable adCompareNotEqual
Value
1 2 0 4 3
Description
Bookmarks are equal First bookmark is after second bookmark First bookmark is before second bookmark Bookmarks cannot be compared Bookmarks are not equal or in order
124
SearchDirectionEnum Constants
Constant
adSearchBackward adSearchForward
Value
-1 1
Description
Searches from the designated starting point backward to the first record Searches from the designated starting point forward to the last record
BookmarkEnum Constants
Constant
adBookmarkCurrent adBookmarkFirst adBookmarkLast
Value
0 1 2
Description
Default, start search at current record Start search at first record Start search at last record
GetRowsOptionEnum Constants
Constant
adGetRowsRest
Value
-1
Description
Default, retrieves all records from the designated starting point to the end of the records
StringFormatEnum Constants
Constant
adClipString
Value
2
Description
Default, delimits columns using the ColumnDelimiter parameter, delimits rows using the RowDelimiter parameter, sets a substitute for Null using the NullExpr parameter
SeekEnum Constants
Constant
adSeekAfter adSeekAfterEQ adSeekBefore adSeekBeforeEQ adSeekFirstEQ adSeekLastEQ
Value
8 4 32 16 1 2
Description
Find a key just after the match to KeyValues Find a key equal to KeyValues or just after the match Find a key just before the match to KeyValues Find a key equal to KeyValues or just before the match Find the first key equal to KeyValues Find the last key equal to KeyValues
125
CursorOptionEnum Constants
Constant
adAddNew adApproxPosition adBookmark adDelete adFind adHoldRecords adIndex adMovePrevious adNotify adResync adSeek adUpdate adUpdateBatch
Value
0x1000400 0x4000 0x2000 0x1000800 0x80000 0x100 0x100000 0x200 0x40000 0x20000 0x200000 0x1008000 0x10000
Description
Supports AddNew method Supports AbsolutePosition and AbsolutePage properties Supports Bookmark property Supports Delete method Supports Find method Supports retrieving more records or changing the position without having to save pending changes Supports Index property Supports GetRows, Move, MoveFirst, and MoveLast methods Supports events Supports Resync method Supports Seek method Supports Update method Supports UpdateBatch and CancelBatch methods
LineSeparatorEnum Constants
Constant
adCR adCRLF adLF
Value
13 -1 10
Description
Carriage return only Default, both a carriage return and a line feed Line feed only
StreamTypeEnum Constants
Constant
adTypeBinary adTypeText
Value
1 2
Description
Binary data Default, text data
StreamOpenOptionsEnum Constants
Constant
adOpenStreamAsync adOpenStreamFromRecord
Value
1 4
Description
Open in an asynchronous mode Already opened Record
126
adOpenStreamUnspecified
-1
StreamReadEnum Constants
Constant
adReadAll adReadLine
Value
-1 -2
Description
Default, read from the current position to EOS Only read until the end of the current line
SaveOptionsEnum Constants
Constant
adSaveCreateNotExist adSaveCreateOverwrite
Value
1 2
Description
Default, creates a new file Completely overwrite data in an existing file
127